xiamx
xiamx

Reputation: 7040

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

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

Upvotes: 4

Views: 6613

Answers (4)

miku
miku

Reputation: 188164

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

Or, if you are confident:

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

Or, the bulletproof version:

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

Upvotes: 6

Dennis Williamson
Dennis Williamson

Reputation: 360585

This should do the trick:

shopt -s extglob
rm !(*.pdf)

Upvotes: 5

Juliano
Juliano

Reputation: 41457

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

Upvotes: 14

TyrantWave
TyrantWave

Reputation: 4673

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

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

Upvotes: -1

Related Questions