[英]Sorting an array of pathnames (strings) [Bash]
我看到過太多重復的記錄,但是沒有任何答案代碼或提示對我有幫助,所以讓我感到困惑。
input=/foo/bar/*;
#Contains something along the lines of
#/foo/bar/file1 /foo/bar/file2 /foo/bar/file3
#And I simply need
#/foo/bar/file3 /foo/bar/file2 /foo/bar/file1
output=($(for l in ${input[@]}; do echo $l; done | sort));
#Doesn't work, returns only the last entry from input
output=$(sort -nr ${input});
#Works, returns everything correctly reversed, but outputs the file contents and not the pathnames;
output=($(sort -nr ${input}));
#Outputs only the last entry and also its contents and not the pathname;
我嘗試了更多的選擇,但是我不會用它們填滿整個頁面,您的要點是。
重復:(沒有一個對我有幫助)
您對bash中的數組感到困惑:這沒有聲明數組:
input=/foo/bar/*
$input
只是字符串"/foo/bar/*"
,文件列表不會被擴展,直到您for i in ${input[@]}
中for i in ${input[@]}
類似的操作for i in ${input[@]}
其中未引用“數組”擴展名)。
你要這個:
input=( /foo/bar/* )
mapfile -t output < <(printf "%s\n" "${input[@]}" | sort -nr)
我沒有時間解釋。 我稍后再來。
您可以sort -r
printf
使用sort -r
,其中input
包含glob字符串以匹配文件名:
sort -r <(printf "%s\n" $input)
這有效:
input=`foo/bar/*`
output=`for l in $input ; do echo $l ; done | sort -r`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.