Delete all files of a particular name & extension except one file.

I wish to delete all files that starts with "body<any number of digits>.xml" except body65.xml on Linux 7 bash shell

So, from the below files

body64.xml
body.sh
body65.xml
body655.xml
body565.xml
body66.xml
hello65.xml

My command should delete all files except the below.

body.sh
body65.xml
hello65.xml

Below is what i tried but it does not fulfill my requirement.

ls| grep -v body65.xml | grep 'body*.xml' | xargs -f rm
ls| grep -v body65.xml | grep "body*.xml" | xargs -f rm
ls| grep -v body65.xml | grep 'body..xml' | xargs -f rm
ls| grep -v body65.xml | grep 'body[[:digit::]].xml' | xargs -f rm
ls| grep -v body65.xml | grep 'body.\.xml' | xargs -f rm

Can you please suggest ?

There seems to be a mixup between shell globs and grep / regex patterns. Try grep 'body.*.xml' .

Or, recent bash es provide "extended pattern matching" if the extglob shell option is set:

shopt -s extglob
echo rm body!(65).xml
rm body565.xml body64.xml body655.xml body66.xml
2 Likes

@RudiC, Thank you for the answer. It worked !!