Sorting on the last field of a line

后端 未结 11 1027
暗喜
暗喜 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:01

    Replace the last delimiter on the line with another delimiter that does not otherwise appear in the list, sort on the second field using that other delimiter as the sort(1) delimiter, and then revert the delimiter change.

    delim=/
    new_delim=" "
    cat $list \
    | sed "s|\(.*\)$delim|\1$new_delim|" \
    | sort -t"$new_delim" -k 2,2 \
    | sed "s|$new_delim|$delim|"
    

    The problem is knowing what delimiter to use that does not appear in the list. You can make multiple passes over the list and then grep for a succession of potential delimiters, but it's all rather nasty - particularly when the concept of "sort on the last field of a line" is so simply expressed, yet the solution is not.

    Edit: One safe delimiter to use for $new_delim is NUL since that cannot appear in filenames, but I don't know how to put a NUL character into a bourne/POSIX shell script (not bash) and whether sort and sed will properly handle it.

提交回复
热议问题