Transpose rows into column in unix

2019-03-21 15:03发布

问题:

I have input file which is given below

Input file

10,9:11/61432568509
118,1:/20130810014023
46,440:4/GTEL
10,9:11/61432568509
118,1:/20130810014023
46,440:4/GTEL

Output which i am looking for.

10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL
10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL

I have tried with awk command, but i am not getting desired output. can anyone help me in this?

awk -F"" '{a[$1]=a[$1]FS$2}END{for(i in a) print i,a[i]}' inputfile

回答1:

Using awk:

$ awk 'ORS=(NR%3==0)?"\n":","' inputfile
10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL
10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL

EDIT: As commented by sudo_O and Ed Morton, the following variant is more portable:

$ awk 'ORS=(NR%3?",":RS)' inputfile
10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL
10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL


回答2:

With pr:

$ pr -ats, file --columns 3  
10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL
10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL

With args and tr:

$ xargs -n3 < file | tr ' ' ,
10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL
10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL


回答3:

Here is how to do it with paste:

paste -d, - - - < file

Output:

10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL
10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL


回答4:

if each of your "data block" has 3 lines, you could do:

sed -n 'N;N;s/\n/,/g;p' file

if you love awk:

awk 'NR%3{printf "%s,",$0;next}7' file


回答5:

> sed 'N;N;s/\n/,/g' your_file


回答6:

A short awk version

awk 'ORS=NR%3?",":RS' file

Shortened, thanks to iiSaymour



回答7:

One way with awk:

$ awk -v RS= -F'\n' 'BEGIN{OFS=","}{for (i=1;i<=NF; i=i+3) {print $i,$(i+1),$(i+2)}}' file
10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL
10,9:11/61432568509,118,1:/20130810014023,46,440:4/GTEL

It defines each field to be a line. Hence, it prints them on blocks of three.