简体   繁体   中英

print out 5 characters in a line bash scripting

I have let say x no of char in a string.
how to print them 5 by 5?
let say

$x = "abcdefghijklmnopqrstuvwxyz"

I wanted to print out like this and store it in a file

abcde
fghij
klmno
pqrst
uvwxy
z

any idea?

edited

somepart of my code

# data file
INPUT=encrypted2.txt
# while loop

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

You can use the fold command:

$ echo "abcdefghijklmnopqrstuvwxyz" | fold -w 5
abcde
fghij
klmno
pqrst
uvwxy
z

The:

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

prints

abcde
fghij
klmno
pqrst
uvwxy
z

Or with your script

input=encrypted2.txt
while read -r -n5 ch
do
    echo "$ch"
done < "$input" >output.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM