Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a list of files with find and grep

Tags:

grep

find

pipe

rm

I want to delete all files which have names containing a specific word, e.g. "car". So far, I came up with this:

find|grep car 

How do I pass the output to rm?

like image 674
Magnus Avatar asked Dec 31 '13 14:12

Magnus


People also ask

How do you find and delete multiple files in Linux?

1) To delete multiple files at once, use the rm command followed by the file names separated by space. This is the traditional method used by newbies. 2) To delete multiple files at once, use the brace expansion as shown below: This example deletes the given files for the month of 'September (09)' .

How do I grep a list of files?

From the grep(1) man page: -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match.


1 Answers

find . -name '*car*' -exec rm -f {} \; 

or pass the output of your pipeline to xargs:

find | grep car | xargs rm -f 

Note that these are very blunt tools, and you are likely to remove files that you did not intend to remove. Also, no effort is made here to deal with files that contain characters such as whitespace (including newlines) or leading dashes. Be warned.

like image 72
William Pursell Avatar answered Sep 29 '22 09:09

William Pursell