Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print out 5 characters in a line bash scripting

Tags:

bash

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"
like image 475
Sharfudin Mohd Ibrahim Avatar asked Dec 26 '22 05:12

Sharfudin Mohd Ibrahim


2 Answers

You can use the fold command:

$ echo "abcdefghijklmnopqrstuvwxyz" | fold -w 5
abcde
fghij
klmno
pqrst
uvwxy
z
like image 130
FatalError Avatar answered Jan 06 '23 06:01

FatalError


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
like image 45
jm666 Avatar answered Jan 06 '23 08:01

jm666