4

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.

2 Answers 2

3

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.

1
  • thanks, works perfectly. Could you maybe add a short sentence about what the -F';' and the $,=";" do?
    – fifaltra
    Dec 9, 2015 at 13:21
1

Assuming homogeneous structure of the data you could use GNU sed and GNU awk to accomplish this, e.g.:

# Separate records by an extra new-line
sed '2~2G' infile |

# Read records and use GNU awk's built-in sort on field 7
awk '
  BEGIN { PROCINFO["sorted_in"] = "@ind_str_desc" }
  { h[$7] = $0 }
  END { for(k in h) print h[k] }
' RS= FS='[;\n]+'

Output:

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .