Find

使用 find -newer 多次處理文件

  • July 6, 2022

我正在嘗試使用 tar(1) 創建比特定文件 ( fileA) 更新的文件的存檔。但是,當我使用 find(1) 獲取要傳遞給 tar 的文件列表時,會多次列出一些文件:

$ touch fileA
$ mkdir test
$ touch test/{fileB,fileC}
$ tar -c -v $(find test -newer fileA) > test.tar
test/
test/fileC
test/fileB
test/fileC
test/fileB

使用 xargs(1) 將文件列表傳遞給 tar 會導致類似的行為:

$ find test -newer fileA | xargs tar -c -v > test.tar
test/
test/fileC
test/fileB
test/fileC
test/fileB

使用 sort(1) 和 uniq(1) 刪除重複項也不起作用:

$ find test -newer fileA | sort | uniq | xargs tar -c -v > test.tar
test/
test/fileC
test/fileB
test/fileB
test/fileC

有沒有辦法讓 tar 只包含比fileA一次更新的每個文件?

**編輯:**我正在專門尋找一個不涉及 tar 的 GNU 擴展的解決方案(例如,它可以與suckless tar一起使用)。

find test -newer fileA

找到test目錄以及其中的單個文件,因此tar添加test(及其所有內容),test/fileB然後test/fileC.

收緊你的find以避免這種情況:

tar -c -v $(find test -type f -newer fileA) > test.tar

請注意,以這種方式使用命令替換可能會導致問題,例如包含空格或萬用字元的文件名;為避免這種情況,請使用

find test -type f -newer fileA -print0 | tar -c -v --null -T- -f - > test.tar

(使用 GNUfindtar),或

find test -type f -newer fileA -exec tar cvf - {} + > test.tar

(假設您沒有太多要歸檔的文件)。

引用自:https://unix.stackexchange.com/questions/708823