如果您使用的是简洁的命令,那么使用bash 中的扩展通配符,您应该能够使用:
rm !(abc.txt)
Run Code Online (Sandbox Code Playgroud)
然而,这种方法有几个注意事项。
这将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.
Run Code Online (Sandbox Code Playgroud)如果!(abc.txt)返回一个很长的文件列表,您可能会得到臭名昭著的“参数列表太长”错误。再次,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
Run Code Online (Sandbox Code Playgroud)
您可以使用 nullglob 解决此问题,但通常使用find. 为了说明,可能的解决方法是:
shopt -s nullglob
F=(!(abc.txt)); if [ ${#F[*]} -gt 0 ]; then rm !(abc.txt); fi # not pretty
Run Code Online (Sandbox Code Playgroud)