Inverse Globbing

March 28, 2015

It felt like a command-line blind spot: is it possible to invert a glob?

What’s the opposite of rm *.mp3? How would you delete everything except the MP3 files?

It turns out that there’s a syntax for that:

rm !(*.mp3)

if you put shopt -s extglob in your .bashrc. There are no downsides to using that config. Extended globbing allows you to do other things too.

Without extended globbing, you could try:

rm $(ls | grep -v mp3$)

but that won’t account for filenames with spaces and other characters that would need to be escaped.

Discuss on Twitter