Saturday, May 24, 2008

Combine 4 rows into 1 row : awk & paste


Input File:

$ cat myfile2.txt
242313
35.6
5.8
1987
543434
45.6
5.11
1985
427672
67
6
1982


Required: Combine every 4 line as 1 single line

i.e. required output:

ID Wt Ht DOB
242313 35.6 5.8 1987
543434 45.6 5.11 1985
427672 67 6 1982


Using paste:

$ echo "ID Wt Ht DOB" ;< myfile2.txt paste - - - -


Using Awk:

$ awk 'BEGIN {print "ID\tWt\tHt\tDOB"} {printf("%s",NR%4 ? $0"\t" : $0"\n")}' myfile2.txt


Explaination:

- NR being the line number.
- NR%4, if not true add a tab, if true add a newline(\n)


A similar post, if I had to make a paragraph of every 4 rows in myfile2.txt, here is a way

1 comment:

Unknown said...

< file.txt \
sed -e '
1i\
ID Wt Ht DOB
:loop
$bend; N
s/\n/&/3
Tloop
:end
y/\n/ /
' |
sed -e '
1i\
.TS\
center,tab( );\
c c c c\
l n n l.
$a\
.TE
' | tbl - | nroff -Tascii -ms | grep '.'

© Jadu Saikia www.UNIXCL.com