Transpose rows into column in unix

风流意气都作罢 提交于 2019-12-03 08:37:31
devnull

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

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

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

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
> sed 'N;N;s/\n/,/g' your_file

A short awk version

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

Shortened, thanks to iiSaymour

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!