Sort – How to Sort File but Keep Pairs of Lines Together

sort

I have a file, with entries of the structure

a1;b1;c1;
d1;e1;f1;g1
a2;b2;c2;
d2;e2;f2;g2

etc.

I want to sort this file via the g's, but keep the abc's with the corresponding g.
Is there any nice way of doing this via the command line? All I can think of right now is to write a more or less elaborate perl script.

Best Answer

If your lines are guaranteed to come in pairs with three fields on the first and 4 on the second (and the second line contains the "g" value):

$ sed -n 'N;s/\n//;p' your_file \
   | sort -t';' -k7 \
   | perl -F';' -ane '$,=";";print @F[0..2],"\n";print @F[3..$#F]'

The sed part joins together every two consecutive lines, sort sorts the input on the seventh field as delimited by ; and finally the perl splits each line into 2: one with three fields and one with four.

Related Question