7

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.

Amit
  • 119
  • 1
  • 7

7 Answers7

10
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}'
Thamme Gowda
  • 9,459
  • 1
  • 41
  • 50
Ed Morton
  • 157,421
  • 15
  • 62
  • 152
8

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

xargs -n2 < file
Kent
  • 173,042
  • 30
  • 210
  • 270
1

One way is:

awk '{ printf("%-10s ",$0); if(NR%2==0) printf("\n");}' file

See it

codaddict
  • 410,890
  • 80
  • 476
  • 515
  • Thank you for the one liner, it really works fine. I have just started learning awk and if I could ask you a bit more, I guess printf("%-10s ",$0) will print every thing in a line, but I could not understand after this. Thanks again. – Amit Dec 28 '12 at 10:25
  • `printf` prints without a newline and `%s` is the format specification for a string. `%-10s` will pad with spaces to a length of 10, left justified, or truncate a longer string. I would actually `printf("%s ", $0)` instead, with a space after %s, alternatively a tab character, `\t`. – tripleee Dec 28 '12 at 14:12
  • 1
    printf is a builtin, not a function, so the () don't do what you think they do, the trailing semi-colon is superflous, and the way to print a newline is `print ""`. – Ed Morton Dec 29 '12 at 22:21
1

sed is better to do this than awk:

sed 'N;s/\n/ /g' yourfile

also in awk:

awk '{if(NR%2!=0){p=""}else{p="\n"};printf $0" "p}' your_file

also check another solution here

Vijay
  • 59,537
  • 86
  • 209
  • 308
1

I'd be tempted to use sed like this:

sed 'N;s/\n/ /' file

However, this won't nicely format your data. You could pipe it into column -t:

< file sed 'N;s/\n/ /' | column -t

But this seems unnecessary. It would be better to use paste like this:

paste - - < file

Results:

John    30
Mike    0.0786268
Tyson   0.114889
Gabriel 0.176072
Fiona   0.101895
Steve
  • 41,445
  • 12
  • 83
  • 96
0
awk 'NR%2{s=$0; next} {print s, $0}' file

or using default action

awk 'NR%2{s=$0; next} {$0=s" "$0}1' file
slitvinov
  • 5,273
  • 15
  • 25
0
paste - - < file > newfile

paste uses tab as a separator by default.

glenn jackman
  • 207,528
  • 33
  • 187
  • 305