簡體   English   中英

對路徑名(字符串)數組進行排序[Bash]

[英]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;

我嘗試了更多的選擇,但是我不會用它們填滿整個頁面,您的要點是。

重復:(沒有一個對我有幫助)

如何在linux bash shell中對字符串數組進行排序?

如何在BASH中對數組排序

自定義排序bash數組

按字母順序排序bash參數

您對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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM