bash 需要一个删除除 *.pdf 之外的所有文件的 shell 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4702577/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:16:48  来源:igfitidea点击:

Need a shell script that deletes all files except *.pdf

bashshellshdelete-file

提问by xiamx

Can anyone write a shell script that deletes all the files in the folder except those with pdfextension?

任何人都可以编写一个shell脚本来删除文件夹中除pdf扩展名之外的所有文件吗?

回答by Juliano

This will include all subdirectories:

这将包括所有子目录:

find . -type f ! -iname '*.pdf' -delete

This will act only in the current directory:

这只会在当前目录中起作用:

find . -maxdepth 1 -type f ! -iname '*.pdf' -delete

回答by miku

$ ls -1 | grep -v '.pdf$' | xargs -I {} rm -i {}

Or, if you are confident:

或者,如果您有信心:

$ ls -1 | grep -v '.pdf$' | xargs -I {} rm {}

Or, the bulletproofversion:

或者,防弹版本:

$ find . -maxdepth 1 -type f ! -iname '*.pdf' -delete

回答by Paused until further notice.

This should do the trick:

这应该可以解决问题:

shopt -s extglob
rm !(*.pdf)

回答by TyrantWave

ls | grep -v '.pdf$' | xargs rm

This will filter all files that don't end in PDF, and execute RM on them

这将过滤所有不以 PDF 结尾的文件,并对它们执行 RM