Transpose rows into a column in unix

I have an input file that is 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 

The result I'm 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 tried with awk command, but I do not get the desired output. can anyone help me with this?

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

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 sudo_O and Ed Morton commented, the next option 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 
+6
source

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 
+4
source

Here's 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
source

if each of your "data blocks" has 3 lines, you can do:

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

if you like awk:

 awk 'NR%3{printf "%s,",$0;next}7' file 
+2
source
 > sed 'N;N;s/\n/,/g' your_file 
+1
source

Short awk option

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

Reduce thanks to iiSaymour

+1
source

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 as a string. Consequently, he prints them on blocks of three.

0
source

All Articles