Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print every 4 columns to one row in perl or awk

Tags:

awk

perl

would you please help me how to convert every 4-sequantial rows into one tab-separated column?

convert:

A
1
2
3
3
3
4
1

to :

A   1  2  3
3   3  4  1
like image 705
EpiMan Avatar asked Dec 20 '22 20:12

EpiMan


2 Answers

A simple way to do this is to use xargs:

$ xargs -n4 < file
A 1 2 3
3 3 4 1

With awk you would do:

$ awk '{printf "%s%s",$0,(NR%4?FS:RS)}' file
A 1 2 3
3 3 4 1

Another flexible approach is to use pr:

$ pr -tas' ' --columns 4 file
A 1 2 3
3 3 4 1

Both the awk and pr solution can be easily modified to change the output separator to a TAB:

$ pr -at --columns 4 file
A         1         2             3
3         3         4             1                        

$ awk '{printf "%s%s",$0,(NR%4?OFS:RS)}' OFS='\t' file
A         1         2             3
3         3         4             1
like image 123
Chris Seymour Avatar answered Dec 31 '22 10:12

Chris Seymour


$ perl -pe 's{\n$}{\t} if $. % 4' old.file > new.file

or simply (thanks to mpapec's comment):

$ perl -pe 'tr_\n_\t_ if $. % 4' old.file > new.file
like image 35
Zaid Avatar answered Dec 31 '22 09:12

Zaid