在 Bash 脚本中每行打印出 5 个字符

4

我有一个字符串,里面有x个字符。
如何每五个字符打印一次?
假设:

$x = "abcdefghijklmnopqrstuvwxyz"

我希望您能像这样打印并将其存储在文件中
abcde
fghij
klmno
pqrst
uvwxy
z

有什么想法吗?

编辑过的

我的代码的一部分

# data file
INPUT=encrypted2.txt
# while loop

while IFS= read -r -n1 char
do
        # display one character at a time
    echo "$char"
done < "$INPUT"

你已经尝试过什么了吗?这不是免费的编码服务。 - The Blue Dog
for ((i=0;i<5;i++)) do while IFS= read -r -n1 char do # 逐个显示字符 echo "$char" done < "$INPUT" done - Sharfudin Mohd Ibrahim
@TheBlueDog 噢,如何以代码形式回复? - Sharfudin Mohd Ibrahim
只需编辑您的问题以包含您的代码。 - The Blue Dog
2个回答

9
你可以使用fold命令:
$ echo "abcdefghijklmnopqrstuvwxyz" | fold -w 5
abcde
fghij
klmno
pqrst
uvwxy
z

+1 我喜欢这些我从未听说过的单一用途的Unix命令。 - martin
好的,我已经编辑了我的代码(基本上删除了我的 while 循环并只使用了 fold 命令)。它完美地工作了!谢谢大家。 - Sharfudin Mohd Ibrahim

2

这是:

grep -Po '.{5}|.*' <<< "abcdefghijklmnopqrstuvwxyz"
#or
grep -Po '.{1,5}' <<< "abcdefghijklmnopqrstuvwxyz" #@Cyrus

打印

abcde
fghij
klmno
pqrst
uvwxy
z

或者使用您的脚本。
input=encrypted2.txt
while read -r -n5 ch
do
    echo "$ch"
done < "$input" >output.txt

或者 grep -Po '.{1,5}' - Cyrus
@Cyrus - :) 需要去睡觉了。有时候我会想得太复杂了。谢谢。 - clt60

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接