How do I remove multiple files with a common prefix and suffix?

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

Although jw013's answer is correct w.r.t globbing, that command may fail if you have thousands of matches: the expanded command line rm sequence_1_0001.hmf sequence_1_0002.hmf ... generated by the shell may simply be too big.

As Dom suggested, you can also use the -delete option with find:

find . -maxdepth 1 -type f -name 'sequence_1*.hmf' -delete

Both -maxdepth and -delete, while not in the POSIX standard are fairly common in find implementations in the wild. Linux distributions generally use GNU find, which certainly supports those options.


rm sequence_1_{0000..0999}.hmf
rm sequence_1_{1000..1999}.hmf
rm sequence_1_{2000..2999}.hmf
...

would work too in Bash.

Tags:

Files