Ehsan Sarshar
Ehsan Sarshar

Reputation: 3211

how to delete files have specific pattern in linux?

I have a set of images like these

12345-image-1-medium.jpg 12345-image-2-medium.png 12345-image-3-large.jpg

what pattern should I write to select these images and delete them

I also have these images that don't want to select

12345-image-profile-small.jpg 12345-image-profile-medium.jpg 12345-image-profile-large.png

I have tried this regex but not worked

1234-image-[0-9]+-small.*

I think bash not support regex as in Javascript, Go, Python or Java

Upvotes: 5

Views: 10441

Answers (3)

Ehsan Sarshar
Ehsan Sarshar

Reputation: 3211

Ok I solve it with this pattern

12345-image-*[0-9]-*

eg:

rm -rf 12345-image-*[0-9]-*

it matches all the file names start with 12345-image- then a number then - symbol and any thing after that

as I found it's globbing in bash not regex and I found this app really use full

Upvotes: 6

David C. Rankin
David C. Rankin

Reputation: 84541

So long as you do NOT have filenames with embedded '\n' character, then the following find and grep will do:

find . -type f | grep '^.*/[[:digit:]]\{1,5\}-image-[[:digit:]]\{1,5\}'

It will find all files below the current directory and match (1 to 5 digits) followed by "-image-" followed by another (1 to 5 digits). In your case with the following files:

$ ls -1
123-image-99999-small.jpg
12345-image-1-medium.jpg
12345-image-2-medium.png
12345-image-3-large.jpg
12345-image-profile-large.png
12345-image-profile-medium.jpg
12345-image-profile-small.jpg

The files you request are matched in addition to 123-image-99999-small.jpg, e.g.

$ find . -type f | grep '^.*/[[:digit:]]\{1,5\}-image-[[:digit:]]\{1,5\}'
./123-image-99999-small.jpg
./12345-image-3-large.jpg
./12345-image-2-medium.png
./12345-image-1-medium.jpg

You can use the above in a command substitution to remove the files, e.g.

$ rm $(find . -type f | grep '^.*/[[:digit:]]\{1,5\}-image-[[:digit:]]\{1,5\}')

The remaining files are:

$ l1
12345-image-profile-large.png
12345-image-profile-medium.jpg
12345-image-profile-small.jpg

If Your find Supports -regextype

If your find supports the regextype allowing you to specify which set of regular expression syntax to use, you can use -regextype grep for grep syntax and use something similar to the above to remove the files with the -execdir option, e.g.

$ find . -type f -regextype grep -regex '^.*/[[:digit:]]\+-image-[[:digit:]]\+.*$' -execdir rm '{}' +

I do not know whether this is supported by BSD or Solaris, etc.., so check before turning it loose in a script. Also note, [[:digit:]]\+ tests for (1 or more) digits and is not limited to 5-digits as shown in your question.

Upvotes: 1

hippodev
hippodev

Reputation: 91

for pic in 12345*.{jpg,png};do rm $pic;done

for more information on wildcards take a look here

Upvotes: 1

Related Questions