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

Can someone write a shell script that will delete all files in the folder except those that have the pdf extension?

+4
source share
4 answers

This will include all subdirectories:

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

This will only work in the current directory:

 find . -maxdepth 1 -type f ! -iname '*.pdf' -delete 
+14
source
 $ ls -1 | grep -v '.pdf$' | xargs -I {} rm -i {} 

Or, if you are sure:

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

Or a bulletproof version:

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

This should do the trick:

 shopt -s extglob rm !(*.pdf) 
+5
source
 ls | grep -v '.pdf$' | xargs rm 

This will filter all files that do not end in PDF, and execute RM on them.

-1
source

Source: https://habr.com/ru/post/1335691/


All Articles