我需要删除当前目录中的所有文件,除了一个文件,比如 abc.txt。是否有任何命令可以 rm 目录中除 abc.txt 之外的所有其他文件?
问问题
2076 次
4 回答
5
如果您使用简洁的命令,那么在 bash 中使用扩展的通配符,您应该能够使用:
rm !(abc.txt)
然而,这种方法有几个注意事项。
这将
rm
在目录中的所有条目上运行(“abc.txt”除外),其中包括子目录。因此,如果存在子目录,您最终会遇到“无法删除目录”错误。如果是这种情况,请find
改用:find . -maxdepth 1 -type f \! -name "abc.txt" -exec rm {} \; # omit -maxdepth 1 if you also want to delete files within subdirectories.
如果
!(abc.txt)
返回一个很长的文件列表,你可能会得到臭名昭著的“argument list too long”错误。再次,find
将是解决此问题的方法。rm !(abc.txt)
如果目录为空或 abc.txt 是唯一的文件,则会失败。例子:[me@home]$ ls abc.txt [me@home]$ rm !(abc.txt) rm: cannot remove `!(abc.txt)': No such file or directory
您可以使用 nullglob 解决此问题,但简单地使用它通常会更干净
find
。为了说明,一个可能的解决方法是:shopt -s nullglob F=(!(abc.txt)); if [ ${#F[*]} -gt 0 ]; then rm !(abc.txt); fi # not pretty
于 2012-09-17T09:23:52.243 回答
3
1)
mv abc.txt ~/saveplace
rm *
mv ~/saveplace/abc.txt .
2)
find . ! -name abc.txt -exec rm {} "+"
于 2012-09-17T10:35:18.757 回答
2
尝试
find /your/dir/here -type f ! -name abc.txt -exec rm {} \;
于 2012-09-17T09:29:25.937 回答
1
如果您没有名称中包含空格的文件,则可以使用 afor
来循环结果ls
:
for FILE in `ls -1`
do
if [[ "$FILE" != "abc.txt" ]]; then
rm $FILE
fi
done
可以写成脚本,也可以直接在 bash 提示符下写:写第一行,然后按enter
,然后你可以写其他行,bash 会等你写完done
再执行。否则,您可以在一行中编写:
for FILE in `ls -1`; do if [[ "$FILE" != "abct.txt" ]]; then rm $FILE; fi; done
于 2012-09-17T09:28:15.840 回答