Search code examples
bashshellsortingtext

sort lines by the last "element" [non-csv text file]


for lines with same number of columns separated by a dot delimiter, like

aa.bb
cc.dd
...

it's easy to sort by last column

sort -t. -k2,2 file

if the text file have different "columns", like

aa.b.xb
cc.dd
xx.cc.aa
a.b.c.d.e
...

then how to sort the lines by the last "column"

xx.cc.aa
cc.dd
a.b.c.d.e
aa.b.xb
...

Solution

  • You can make use of the Schwartzian transform in bash.

    awk -F. '{print $NF "\t" $0}' file | sort -k1,1 | cut -f2-
    
    • First extract the last column and prepend it to the line delimited by a tab character.
    • Then sort the lines with the 1st (prepended) column.
    • Finaly remove the 1st column with cut command.