删除文本文件中列出的文件

我有一个文件,导出了一堆需要删除的文件名。 我需要知道如何去除每个文件,而不必一次一个在命令行上发布。

我曾经想过只是在for循环中进行操作,这可能会起作用,但是想知道是否有一个更简单,甚至更好的解决scheme。

谢谢。

 rm -rf `cat /path/to/filename` 

“可以用$()replace字符

来自bash手册页:

  Command Substitution Command substitution allows the output of a command to replace the command name. There are two forms: $(command) or `command` Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file). When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially. Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes. If the substitution appears within double quotes, word splitting and path‐ name expansion are not performed on the results. 

不需要cat或一个循环:

 xargs -d '\n' -a file.list rm 
 $ cat file.list | xargs rm 
 while read filename ; do rm "$filename" ; done < files.lst 
 perl -lne 'unlink' files_to_remove.txt 

如果你需要删除大量的文件,这比xargs + rm快好几倍,比shell循环快许多倍。

只是为了它的地狱,只需将文件制作成一个脚本,并执行它处理空白和大多数其他尴尬的人物,很简单。 不会产生比上述大多数方法更多的进程。

 sed -ie 's/^/rm -f "/;s/$/"/' <filename> sh <filename> 

目前的答案是足够的 – 如果你有太多的文件,xargs可能会失败 – 在这种情况下,你将需要某种循环。

另外 – 当执行这种事情时,不删除,而是将文件移动到另一个文件夹是一个不错的主意,所以你可以手动validation一些奇怪的文件名没有犯一些错误。 然后,当你确信你没事的时候,只要删除文件夹。

不是最好的,但它的作品 – 🙂

 cat myfile | awk '{print "rm -rf " $0}' | bash