Sorting on the last field of a line

后端 未结 11 987
暗喜
暗喜 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 04:50

    something like this

    awk '{print $NF"|"$0}' file | sort -t"|" -k1 | awk -F"|" '{print $NF }'
    
    0 讨论(0)
  • 2020-12-05 04:50

    I want this list sorted on the filenames, which all start with numbers indicating the order the files should be read.

    find . | sed 's#.*/##' | sort
    

    the sed replaces all parts of the list of results that ends in slashes. the filenames are whats left, and you sort on that.

    0 讨论(0)
  • 2020-12-05 04:53
    | sed "s#(.*)/#\1"\\$'\x7F'\# \
    | sort -t\\$'\x7F' -k2,2 \
    | sed s\#\\$'\x7F'"#/#"
    

    Still way worse than simple negative field indexes for sort(1) but using the DEL character as delimiter shouldn’t cause any problem in this case.

    I also like how symmetrical it is.

    0 讨论(0)
  • 2020-12-05 04:59

    I think the only solution would be to use awk:

    1. Put the last field to the front using awk.
    2. Sort lines.
    3. Put the first field to the end again.
    0 讨论(0)
  • 2020-12-05 05:00

    A one-liner in perl for reversing the order of the fields in a line:

    perl -lne 'print join " ", reverse split / /'
    

    You could use it once, pipe the output to sort, then pipe it back and you'd achieve what you want. You can change / / to / +/ so it squeezes spaces. And you're of course free to use whatever regular expression you want to split the lines.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题