將 cat 輸出提供給 rm

將 cat 輸出提供給 rm

我的檔案中有檔名,需要在不同的目錄中刪除該檔案。

假設我在 dir 中有x和文件。如何使用cat刪除它?ya

我試過,

rm -f a/{`cat a.txt`}

a.txt有內容x,y,z

如果它們位於同一資料夾中,我可以放入x y za.txt運行,

rm -f `cat a.txt`

效果很好。

我也嘗試過,

rm -f "a/{"`cat a.txt`"}"

該命令將放入 dockerfile 中,因此我也不喜歡使用任何變數。

不要想要放入a/x a/y a/z的檔案可以是一個選項,因為它是固定的,a只包含檔案。但a只能在 dockerfile 中更改。在此先感謝所有建議:)

答案1

您應該使用 while 循環逐行讀取文件,然後將每一行應用於rm.這是腳本編寫中非常常見且經常使用的方法

while IFS= read -r line
do
       rm a/"$line"
done < file.txt

當然,文件的格式應該是文件列表,每行一個文件

答案2

不要嘗試用於$(cat file)此類事情 - 例如,如果給定的檔案名稱中有空格,它會中斷

$ cat a.txt 
foo
bar baz
bam

$ ls -Q a
"bam"  "bar baz"  "foo"  "other file"  "somefile"

然後

$ (cd a ; rm $(cat ../a.txt))
rm: cannot remove 'bar': No such file or directory
rm: cannot remove 'baz': No such file or directory

相反,您可以使用xargs

$ ls -Q a
"bam"  "bar baz"  "foo"  "other file"  "somefile"
$ xargs -a a.txt -I{} rm a/{}
$ ls -Q a
"other file"  "somefile"

如果你真的想要使用cat,然後將其與xargs

cat a.txt | xargs -I{} rm a/{}

(儘管考慮到該-a功能,它是一個貓的無用使用


請注意,這-I{}意味著-L 1ierm對輸入檔的每一行調用一次;如果您不需要在前面新增目錄路徑,那麼您可以透過取消將-I多個xargs參數傳遞給rm.但是,在這種情況下,您應該明確地將輸入分隔符號設定為換行符,例如xargs -a a.txt -d '\n' rm以防止空格中斷。

答案3

假設您的檔案名稱不包含空格或任何特殊字符,只需在cd其前面重複使用原始命令即可:

(cd a; rm -f $(cat a.txt))

請注意,rm -f `cat a.txt`檔案名稱中的空格或任何特殊字元很容易中斷,您應該真正使用xargsNUL 分隔的檔案名稱。

相關內容