Linux 当名称不包含某些单词时删除文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6562156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
remove files when name does NOT contain some words
提问by DocWiki
I am using Linux and intend to remove some files using shell.
我正在使用 Linux 并打算使用 shell 删除一些文件。
I have some files in my folder, some filenames contain the word "good", others don't. For example:
我的文件夹中有一些文件,一些文件名包含“好”这个词,其他的则没有。例如:
ssgood.wmv
ssbad.wmv
goodboy.wmv
cuteboy.wmv
I want to remove the files that does NOT contain "good" in the name, so the remaining files are:
我想删除名称中不包含“good”的文件,所以剩下的文件是:
ssgood.wmv
goodboy.wmv
How to do that using rm
in shell? I try to use
如何rm
在shell中使用它?我尝试使用
rm -f *[!good].*
but it doesn't work.
但它不起作用。
Thanks a lot!
非常感谢!
采纳答案by EdoDodo
This command should do what you you need:
这个命令应该做你需要的:
ls -1 | grep -v 'good' | xargs rm -f
It will probably run faster than other commands, since it does not involve the use of a regex (which is slow, and unnecessary for such a simple operation).
它可能会比其他命令运行得更快,因为它不涉及使用正则表达式(这很慢,对于这样简单的操作来说是不必要的)。
回答by T.J. Crowder
You can use find
with the -not
operator:
您可以find
与-not
运算符一起使用:
find . -not -iname "*good*" -a -not -name "." -exec rm {} \;
I've used -exec
to call rm
there, but I wonder if it does, see below.find
has a built-in delete action
我曾经-exec
在rm
那里打电话,但我想知道它是否,见下文。find
有内置的删除操作
But verycareful with that. Note in the above I've had to put an -a -not -name "."
clause in, because otherwise it matched .
, the current directory. So I'd test thoroughly with -print
before putting in the -exec rm {} \;
bit!
但对此非常小心。请注意,在上面我不得不放入一个-a -not -name "."
子句,否则它会匹配.
当前目录。所以我会-print
在投入之前彻底测试-exec rm {} \;
!
Update: Yup, I've never used it, but there is indeed a -delete
action. So:
更新:是的,我从来没有用过它,但确实有一个-delete
动作。所以:
find . -not -iname "*good*" -a -not -name "." -delete
Again, be careful and double-check you're not matching more than you want to match first.
同样,要小心并仔细检查您匹配的次数没有超过您想要匹配的次数。
回答by glenn Hymanman
With bash, you can get "negative" matchingvia the extglob
shell option:
使用 bash,您可以通过shell 选项获得“否定”匹配extglob
:
shopt -s extglob
rm !(*good*)