Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moving every second row to a new column with awk

Tags:

awk

Here is another noob question. I have a file like this

John
30
Mike
0.0786268
Tyson
0.114889
Gabriel
0.176072
Fiona
0.101895

I need to shift every second row to a new column so it should look like this

John   30
Mike   0.0786268
Tyson  0.114889
Gabriel 0.176072
Fiona   0.101895

I just now that awk 'NR%2==0' will print every second row, could somebody suggest me how to shift them to a new column as above. Any help is most appreciated.

like image 878
Amit Avatar asked Dec 28 '12 09:12

Amit


2 Answers

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

Explanation:

  • printf will not include a new line character at the end of line (unlike print)
  • (NR%2?FS:RS) decides new line (RS) or field seperator (FS) based on NR%2

If your colmns should be seperated by \t

awk '{printf "%s%s",$0,NR%2?"\t":RS}'
like image 72
Ed Morton Avatar answered Sep 28 '22 08:09

Ed Morton


xargs could do it, the command line is really short:

xargs -n2 < file
like image 45
Kent Avatar answered Sep 28 '22 08:09

Kent