Piping grep to rm

I discovered a neat trick to deleting folders/files based on a pattern. Let’s say you have a directory structure like this:

/test
/test/aaaa
/test/bbbb
/test/cccc
/test/ddd
/test/eee
/test/fff

You’ve decided that any folder with a’s, b’s, or c’s has to go. You definitely don’t want to delete them all by hand; especially if there are a couple thousand of them. The first thing you need to do is find the directories that you want to remove:

  1. ls | grep "[a-c]"

Which produces the following:
aaaa
bbbb
cccc

Great! Now what? All you need to do is pipe that to rm using xargs:

  1. ls | grep "[a-c]" | xargs rm -rf

All files that match the given pattern will be deleted. But, be careful that the pattern only matches the files you would like to delete. Run ls | grep first before you pipe anything to rm, unless you like trying to restore deleted files.

Technorati :

One Response to “Piping grep to rm”

  1. Pranab Says:

    Thank you. I was looking for this solution.
    Regards,
    Pranab Sharma
    http://www.goguwahati.com

Leave a Reply