How to sort with a delimiter that is several characters long

sort

INPUT:

$ cat a.txt 
1FOO2FOO3
4FOO5FOO5
2FOO1FOO9
$ 

OUTPUT:

$ cat a.txt | sort SOMEMAGIC
2FOO1FOO9
1FOO2FOO3
4FOO5FOO5
$ 

Question: How can I sort, if I have a several character long delimiter? ("FOO")?

In the example a.txt is sorted by second column.

Question is in general, numbers in a.txt could be anything.

Best Answer

Use e.g. sed to replace the string with a one-character delimiter, sort by the column, and then replace the delimiter back again:

sed -e s/FOO/X/g a.txt | sort -k 2,2 -t X | sed -e s/X/FOO/g 

This assumes that there is a character that you know doesn't appear in the input. A control character would be a common candidate, but you need to make a choice based on your knowledge of the input format.

Related Question