Remove files in a directory based on partial name

16,476

Solution 1

The simple way:

cd /path/to/directory
rm *_foo_*

or

rm /path/to/directory/*_foo_*

The asterisk (*) matches all characters.

To get explanations about what is being done, use rm with -v option. To be prompted before every removal, use rm with -i option:

rm -vi *_foo_*

See man rm for more info.

Solution 2

If you want to do it in all subdirectories too, the easiest way is to enable the globstar shell option:

shopt -s globstar
rm **/*foo_*

There should be a commented (i.e. starting with a #) line in the default ~/.bashrc (line 29 in mine):

# shopt -s globstar extglob

Just uncomment that line and you'll have access to some improved bash features.

Share:
16,476

Related videos on Youtube

Ilia Hanev
Author by

Ilia Hanev

I am an evil overlord that is sometimes mis-judged. I love walks in the park under a lightning storm and driving around my Death Star through the Galaxy. People have been known to find me writing code for websites, light saber drawing in Illustrator on my Wacom, building apps to do something because I'm lazy or using the force to market my campaign on why the Rebels need to be demolished.

Updated on September 18, 2022

Comments

  • Ilia Hanev
    Ilia Hanev over 1 year

    I wanted to know what is the best way to remove any files no matter what their extension is based on a partial name.

    Example:

    13-05-12_foo_something.jpg
    13-06-01_something.png
    13-05-05_foo_site.html
    

    rm everything in a directory and within the sub folders with _foo_ in the name.

  • Ilia Hanev
    Ilia Hanev over 10 years
    Thanks I was unaware you could do that with * before and after.
  • Radu Rădeanu
    Radu Rădeanu over 10 years
    @Matt_2.0 You can use it as many times as you want: rm *foo_1*foo_2*...*foo_n*