Friday, February 29, 2008

Split a line into lines - AWK or SED


We can use "jot" to print A-Z like below:

$ jot -c 26 A | tr '\n' ' '
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

The required Output:

A B C D
E F G H
I J K L
M N O P
Q R S T
U V W X
Y Z

i.e in one line, 4 alphabets.

Solution:

4 alphabets means including spaces, its 8 characters in one line.

$ jot -c 26 A | tr '\n' ' ' | sed -e "s/.\{8\}/&\n/g"

One solution using AWK:

$ jot -c 26 A | tr '\n' ' ' | awk 'BEGIN{n=1}{while(substr($0,n,8)){print substr($0,n,8);n+=8}}'
A B C D
E F G H
I J K L
M N O P
Q R S T
U V W X
Y Z

3 comments:

Anonymous said...

Great stuff :-)

Drey said...

Thanks!
awk split helped me.

Anirudh said...

Actually in this particular
scenario, using "sed" can avoid
heavy lifting...

echo "A B C D ... Z" |
sed -e 's/[ ]/\n/4;P;D'

The '4' gives the 4 chars/line.
YMMV.

© Jadu Saikia www.UNIXCL.com