linux - 读取并删除名称中包含空格的文件

标签 linux shell unix sh

我必须从文件 A.txt 中读取文件名列表,其中文件名中有空格,因此无法删除。文件 A.txt 如下所示

20150726140135_Content 1.mp4
20150726162955_Content 1.mp4
20150726163056_Content 3.mp4
20150726164057_Content 5.mp4
20150726170315_Tab main 2.mp4

for f in $(cat A.txt) ; do 
   rm "/tmp/$f";
done

虽然尝试这个文件分成两部分导致错误

rm: cannot remove `/tmp/20150726170315_Tab': No such file or directory
rm: cannot remove `/tmp/2': No such file or directory

最佳答案

for i in $(cat)

是 bash 中常见的反模式。您不应该使用 for 循环来读取行。这不起作用,因为:

  1. 首先将$(cat A.txt)扩展为20150726140135_Content 1.mp4 20150726162955_内容1.mp4 20150726163056_内容3.mp4 20150726164057_内容5.mp4 20150726170315_Tab main 2.mp4(无引号)。

  2. 然后shell执行命令for i in 20150726140135_Content 1.mp4 20150726162955_Content 1.mp4 20150726163056_Content 3.mp4 20150726164057_Content 5.mp4 20150726170315_Tab main 2.mp4。换行符和空格被解释为参数分隔符。

收件人read a file line by line in bash使用 while IFS= read -r 循环:

while IFS= read -r f; do 
   rm "/tmp/$f";
done < A.txt

关于linux - 读取并删除名称中包含空格的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58395297/

相关文章:

unix:///tmp/supervisor.sock 没有这样的文件

linux - 通过 BASH 用下划线替换空格

linux - pthread_mutex_lock 是如何实现的

具有多个子线程的Java服务

shell - 使用 rot13 和 tr 命令获得加密的电子邮件地址

linux - Docker Bash 提示不显示颜色输出

Windows批处理脚本从文件名中删除括号中的文本?

linux - WebDriver异常: no chrome binary at/usr/bin/google-chrome-stable or chrome binary not found

linux - 通过 zsh 中的参数抑制更正

android - getPsc() 在三星设备上返回 -1。我该怎么做才能让它正常工作?