How to remove multiple files with a common prefix and suffix

files

I have many files named

sequence_1_0001.jpg  
sequence_1_0002.jpg  
sequence_1_0003.jpg  
...

and files named

sequence_1_0001.hmf  
sequence_1_0002.hmf  
sequence_1_0003.hmf  
...

and files named

sequence_2_0001.jpg  
sequence_2_0002.jpg  
sequence_2_0003.jpg  
...

and

sequence_2_0001.hmf  
sequence_2_0002.hmf  
sequence_2_0003.hmf  
...

I just want to remove the files that begin with 'sequence_1' and end in '.hmf', but I don't want to remove them one by one, since there are thousands of files. How can I specify to the rm command that I want to remove all that begin with the prefilx 'sequence_1' and end in '.hmf'?

I'm currently working with a RedHat Linux system, but I'd like to know how to do it on other distributions as well.

Best Answer

rm sequence_1*.hmf

removes files beginning with sequence_1 and ending with .hmf.


Globbing is the process in which your shell takes a pattern and expands it into a list of filenames matching that pattern. Do not confuse it with regular expressions, which is different. If you spend most of your time in bash, the Wooledge Wiki has a good page on globbing (pathname expansion). If you want maximum portability, you'll want to read the POSIX spec on pattern matching as well / instead.


In the unlikely case you run into an "Argument list too long" error, you can take a look at BashFAQ 95, which addresses this. The simplest workaround is to break up the glob pattern into multiple smaller chunks, until the error goes away. In your case, you could probably get away with splitting the match by prefix digits 0 through 9, as follows:

for c in {0..9}; do rm sequence_1_"$c"*.hmf; done
rm sequence_1*.hmf  # catch-all case
Related Question