How do I delete certain files in the current directory that doesn't match the given pattern?

青春壹個敷衍的年華 提交于 2019-12-11 03:29:37

问题


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


回答1:


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.




回答2:


echo $(ls | grep -v '.jar$')

rm $(ls | grep -v '.jar$')



回答3:


You can do this by enabling the extended glob extglob option and then putting your pattern inside !() like so:

shopt -s extglob;
rm !(*.jar)

Note that extglob also gives you the following:

  • ?() -- Match zero or one of the pattern
  • *() -- Match zero or more of the pattern
  • @() -- Match exactly one of the pattern
  • !() -- Match anything except the pattern


来源:https://stackoverflow.com/questions/4262108/how-do-i-delete-certain-files-in-the-current-directory-that-doesnt-match-the-gi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!