2

I have a pipe delimited file like this

    OLD|123432
    NEW|232322
    OLD|1234452
    NEW|232324
    OLD|656966
    NEW|232325

I am trying to create a new file where I am trying to merge rows based on the value in the first column (OLD/NEW). First column in the output file will have the new number and the second column will have the old number.

Output

232322|123432
232324|1234452
232325|656966

I looked at the answer here How to merge every two lines into one from the command line?. I know it is not the exact solution but used as a starting point.

and tried to make it work to solve this but throws syntax error.

awk -F "|" 'NR%2{OFS = "|" printf "%s ",$0;next;}1'
Inian
  • 80,270
  • 14
  • 142
  • 161
Megatron
  • 23
  • 2

2 Answers2

2

You may use this awk:

awk 'BEGIN {FS=OFS="|"} $1 == "NEW" {print $2, old} $1 == "OLD" {old = $2}' file

232322|123432
232324|1234452
232325|656966
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

Using $0 will have the value of the whole line. If the field separator is a pipe, the second column is $2 that has the number.

If you want to use the remainder with NR%2, another option could be storing the value of the second column in a variable, for example v

awk 'BEGIN{FS=OFS="|"} NR%2{v=$2;next;}{print $2,v}' file

Output

232322|123432
232324|1234452
232325|656966
The fourth bird
  • 154,723
  • 16
  • 55
  • 70