如果要删除名称与特定表单匹配的所有文件,则通配符(glob模式)是最直接的解决方案。 一些例子:
$ rm -f abc.log.* # Remove them all
$ rm -f abc.log.2012* # Remove all logs from 2012
$ rm -f abc.log.2012-0[123]* # Remove all files from the first quarter of 2012
正则表达式比通配符更强大; 您可以将ls | grep ...的输出提供给rm -f.例如,如果某些文件名以"abc.log"开头,而某些文件名以"ABC.log"开头,则grep允许您执行不区分大小写的匹配:
$ rm -f $(ls | grep -i '^abc\.log\.')
When I do this, I run the ls | grep ... command first and check that it produces the output I want -- especially if I'm using rm -f:
$ ls | grep -i '^abc\.log\.'
(check that the list is correct)
$ rm -f $(!!)
其中list扩展为上一个命令。 或者我可以键入向上箭头或Ctrl-P并编辑上一行以添加rm -f命令。
This assumes you're using the bash shell. Some other shells, particularly csh and tcsh and some older sh-derived shells, may not support the list syntax. You can use the equivalent backtick syntax:
$ rm -f `ls | grep -i '^abc\.log\.'`
The list syntax is easier to read, and if you're really ambitious it can be nested.
Finally, if the subset of files you want to delete can't be easily expressed with a regular expression, a trick I often use is to list the files to a temporary text file, then edit it:
$ ls > list
$ vi list # Use your favorite text editor
然后我可以手动编辑list文件,只保留我要删除的文件,然后:
$ rm -f $(
要么
$ rm -f `cat list`
(这假设没有文件名包含有趣的字符,特别是空格。)
或者,在编辑list文件时,我可以将rm -f添加到每行的开头,然后:
$ . ./list
要么
$ source ./list