如何删除当前目录中与给定模式不匹配的某些文件? [英] How do I delete certain files in the current directory that doesn't match the given pattern?
问题描述
使用 rm * .sh
删除以.sh结尾的文件是容易和可理解的。但是如何删除在 .jar
结束的当前目录中的所有文件,如 rm * -except * .jar
$ p>
find。 - mindepth 1 --maxdepth 1! -name'* .jar'| sort
如果你真的要删除其输出中的所有文件,
查找。 - mindepth 1 --maxdepth 1! -name'* .jar'-delete
您可以阅读find信息。
编辑:
由于-delete标志只存在于GNU find > 4.2.3(如SiegeX指出),这里有几个选项,它们也确保我们不会删除目录:
find。 - mindepth 1 --maxdepth 1!类型d! -name'* .jar'-print0 | xargs -0 -r rm -f
-r xargs标志是一个GNU扩展,稍微更便携(它工作在* BSD),但不干净:
查找。 - mindepth 1 --maxdepth 1!类型d! -name'* .jar'-print0 | xargs -0 rm -f
作为最后一个,但最便携的度假村:
查找。 - mindepth 1 --maxdepth 1!类型d! -name'* .jar'-exec rm'{}'';'
为每个文件单独调用rm,这使得它明显更慢。
using rm *.sh
to delete files ending in .sh is easy and understandable. But how do i delete all files in the current directory that does not end in .jar
something like rm * -except *.jar
Try this:
find . -mindepth 1 -maxdepth 1 ! -name '*.jar' | sort
If you really want to delete all the files in its output, then just do
find . -mindepth 1 -maxdepth 1 ! -name '*.jar' -delete
You can read the find(1) manual page for more information on this really powerful tool.
EDIT:
Since the -delete flag is only found in GNU find > 4.2.3 (as pointed out by SiegeX), here are a couple of alternatives, which also make sure we are not trying to delete directories:
find . -mindepth 1 -maxdepth 1 ! -type d ! -name '*.jar' -print0 | xargs -0 -r rm -f
The -r xargs flags is a GNU extension, so this is slightly more portable (it works on *BSD), but not as clean:
find . -mindepth 1 -maxdepth 1 ! -type d ! -name '*.jar' -print0 | xargs -0 rm -f
As a last - but most portable - resort:
find . -mindepth 1 -maxdepth 1 ! -type d ! -name '*.jar' -exec rm '{}' ';'
This has the disadvantage of invoking rm separately for each file, which makes it significantly slower.
这篇关于如何删除当前目录中与给定模式不匹配的某些文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!