简体   繁体   中英

BASH order strings by the last “fields” (after “/” symbol")

I'm looking for a method to sort line alphabetically by their last "field". So:

if my output is (maybe by a grep command):

mike/downloads.png
mike/public/system.png
mike/root/alphabet.png

the result should be:

root/alphabet.png
downloads.png
public/system.png

beacuse "alphabet" , "downloads" and "system" are order alphabetically.

should I firts cut and sort them with " cut -f2 -d"/" | sort " ? and then merge the rest of the path?

or there is an easier way?

Any helps will be appreciated.

Thanks

(example modified)

Sort具有-t参数来指定字段定界符,而-k具有指定要排序的字段,因此您可以编写:

sort -t/ -k 3 

Thank you all! I have finally found what i was looking for

first

awk -F'/' '{print $NF,$0}' 

then

sort 

and finally

sed -n 's/[^/]*\///p'

and the output will be

folder/file.png
file.png
folder/folder2/file.png

这指定第三个字段,其字段分隔符为/

sort -t'/' -k 3 

As the number of fields is dynamic you could append the last field to the start of the line before sorting and remove it after:

$ awk -F'/' '{print $NF,$0}' file | sort | awk '{print $2}'
mike/root/alphabet.png
mike/downloads.png
mike/public/system.png

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM