Bash Pattern Matching with rm command

Answer #1 100 %

Just include two patterns in the same rm command:

rm -rf -- \
  *" "*[0-9]*/ \   # this one gets directories with spaces before numbers...
  *[0-9]*" "*/     # ...and this one gets directories with numbers before spaces.

If only one of the two classes exists, then the class that doesn't exist doesn't get expanded (unless the nullglob shell option is enabled). That's harmless, though, since rm -f ignores arguments that don't exist. So, let's say you had a file foo 5, but no files with spaces following the numbers. When you run this, the shell would do the following:

rm -rf -- "foo 5" "*[0-9]* */"

...which is harmless with rm, but might cause some trouble for a non-rm program that requires all arguments it's passed to exist.

To work around that, enable the nullglob option:

shopt -s nullglob

...and then any non-matching patterns will simply be deleted.

Another interesting case is when you want to avoid duplicate names. For instance, client 15 jenkins matches both *" "*[0-9]* and *[0-9]*" "*, so if you put both patterns on a single line, you get that file listed twice. You can avoid this using bash extglobs:

shopt -s extglob # turn on extended globbing
rm -rf -- *@([0-9]*" "|" "*[0-9])*/ # ...and now this will only emit one result
Tags: bash

You’ll also like:

© 2022 CodeForDev.com -