3

I'm trying to sort on multiple columns a file with GNU sort.

The format of the source file tmp/file.txt is :

03A12345679   2014-09-30-00.00.01.00
  • "03" => first column
  • "A" => field separator
  • "12345679 " => second column
  • "2014-09-30-00.00.01.00" => other column (not sorted)

I've tried this command :

sort --field-separator="A" -k2,11 -k1,2 tmp/file.txt > tmp/file_out.txt

With :

  • --field-separator="A" => field separator is "A"
  • -k2,11 => the second column is the first sort ("12345679 ")
  • -k1,2 => the first column is the second sort ("03")

But in the result the sort is not correct (the "03" is before the "01" and "02" lines) :

03A12345679   2014-09-30-00.00.01.000000-0000
01A12345679   12345679  132132155VDVLDLV
02A12345679   FONDSEURO   000012664,120000000M
02A12345679   FR09999956570000009999,999990000F
01A12345680   472958519598601200000000047295824
02A12345680   122121EUR     0000099999,370000000M

I want to have this result :

01A12345679   12345679  132132155VDVLDLV
02A12345679   FONDSEURO   000012664,120000000M
02A12345679   FR09999956570000009999,999990000F
03A12345679   2014-09-30-00.00.01.000000-0000
01A12345680   472958519598601200000000047295824
02A12345680   122121EUR     0000099999,370000000M

How can i do that ?

2
  • Some of these lines look like French bank information. You might want to mask it a little. Dec 19, 2014 at 13:07
  • It's test data. Not real data. Only ISIN code are real but everything else it random data.
    – mr_peck
    Dec 19, 2014 at 15:10

2 Answers 2

4

You seem to be mixing up field positions and character positions. There is no need to split on A; with GNU sort, you can sort on a range of characters within the first space-delimited field:

$ sort -k1.4,1.11 -k1.1,1.2 file
01A12345679   12345679  132132155VDVLDLV
02A12345679   FONDSEURO   000012664,120000000M
02A12345679   FR09999956570000009999,999990000F
03A12345679   2014-09-30-00.00.01.000000-0000
01A12345680   472958519598601200000000047295824
02A12345680   122121EUR     0000099999,370000000M
2

Use -g (compare according to general numerical value) to sort:

sort --field-separator="A" -g -k2,11 -k1,2 tmp/file.txt > tmp/file_out.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.