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"

Upvotes: 4

Views: 198

Answers (2)

clt60
clt60

Reputation: 63922

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

Upvotes: 2

FatalError
FatalError

Reputation: 54551

You can use the fold command:

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

Upvotes: 9

Related Questions