Earlier today, I was in need of an easy way to delete files that mached a specific format within a series of folders. For the case of this example, let's say all CSS files. I discovered I could do it with:

find . -name '*.css' -delete

The . represents the current folder and below. Unfortunately you can't use rm -r because it doesn't recursively check for file names matching a pattern.

If you're using the latest version of macOS where the default shell changed to zsh you can glob it

/tmp
❯ mkdir -p omg/wtf/bbq

/tmp
❯ touch omg/wtf/bbq/{1,2,3,4,5,6,7,8,9,10}.css

/tmp
❯ tree omg
omg
└── wtf
    └── bbq
        ├── 10.css
        ├── 1.css
        ├── 2.css
        ├── 3.css
        ├── 4.css
        ├── 5.css
        ├── 6.css
        ├── 7.css
        ├── 8.css
        └── 9.css

2 directories, 10 files

/tmp
❯ rm -r omg/**/*.css
commented: +1 for Glob. Long live Glob. +15

Also, in addition to find -exec (which is awesome) there's xargs - it works in a very similar fashion but can be used anywhere to do.. anything.

https://en.wikipedia.org/wiki/Xargs

The newer 'find' has a batch execution mode, but I find it easier to use 'xargs'. I usually do 'xargs -n101 ...' to both prevent execution with no arguments and get the work started while still getting 99+% of the bulk savings. In fact, I wrote a fast xargs that does the work of one batch while collecting the input for the next batch without excessive blocking. For the power user, xargs has a high steroids cousing, parallel. Or you can spin off the rm in the bg since there is no output as 'rm some_file &' or batches 'rm some_files &'. Sometime I use:

find ... -type f -name '*.css' | xargs -n101 echo rm | while read l
    do
        $l &
    done

but you have to beware of spaces and such in the file names!

You want to 'find ... -type f', so you are not working on directories, devices, or sym links! When not trying for directories, the '-r' option of rm is not needed.

Thank you it is very useful

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.