Sorting on the last field of a line

后端 未结 11 1001
暗喜
暗喜 2020-12-05 04:06

What is the simplest way to sort a list of lines, sorting on the last field of each line? Each line may have a variable number of fields.

Something like



        
11条回答
  •  温柔的废话
    2020-12-05 05:07

    Here's a Perl command line (note that your shell may require you to escape the $s):

    perl -e "print sort {(split '/', $a)[-1] <=> (split '/', $b)[-1]} <>"
    

    Just pipe the list into it or, if the list is in a file, put the filename at the end of the command line.

    Note that this script does not actually change the data, so you don't have to be careful about what delimeter you use.

    Here's sample output:

    >perl -e "print sort {(split '/', $a)[-1] <=> (split '/', $b)[-1]} " files.txt
    /a/e/f/g/h/01-do-this-first
    /a/b/c/10-foo
    /a/b/c/20-bar
    /a/d/30-bob
    /a/b/c/50-baz
    /a/e/f/g/h/99-local
    

提交回复
热议问题