透過管道傳輸到「sort」指令對「find -print0」的輸出進行排序

透過管道傳輸到「sort」指令對「find -print0」的輸出進行排序

find在將輸出傳遞給命令之前,我需要能夠按字母順序對輸出進行排序。進入| sort |之間不起作用,那我該怎麼辦?

find folder1 folder2 -name "*.txt" -print0 | xargs -0 myCommand

答案1

像往常一樣使用find並用 NUL 分隔行。 GNUsort可以使用 -z 開關來處理這些:

find . -print0 | sort -z | xargs -r0 yourcommand

答案2

某些版本sort有一個-z選項,允許空終止記錄。

find folder1 folder2 -name "*.txt" -print0 | sort -z | xargs -r0 myCommand

此外,您還可以編寫一個高級腳本來執行此操作:

find folder1 folder2 -name "*.txt" -print0 | python -c 'import sys; sys.stdout.write("\0".join(sorted(sys.stdin.read().split("\0"))))' | xargs -r0 myCommand

添加-r選項以xargs確保myCommand使用參數調用它。

答案3

我認為你需要-n排序標誌#

按人排序:

-n, --numeric-sort
    compare according to string numerical value

編輯

print0 可能與此有關,我剛剛測試了這一點。取出 print0 ,您可以使用-z標誌在排序中以 null 終止字串

答案4

一些實現find支援直接透過-s參數進行有序遍歷:

$ find -s . -name '*.json'

從FreeBSD找到手冊頁

-s       Cause find to traverse the file hierarchies in lexicographical
         order, i.e., alphabetical order within each directory.  Note:
         `find -s' and `find | sort' may give different results.

相關內容