Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - how to find and remove all files that contain a given string?

Let's say there's a number of files in a given directory with various file extensions or no extensions at all, just filename. Some of these files include the string "\/for\/endetta".

How do I find and remove all the files in that directory matching this pattern? I could do sort of do this by using:

find -type f -exec egrep -Il '\/for\/endetta' {} \;|xargs rm -fv
  1. But is it possible to do it without xargs?

  2. And how do I properly escape the \s and /s, etc.

like image 483
Sami88 Avatar asked Oct 27 '25 13:10

Sami88


2 Answers

BrowSlow's answer (in the comments) is correct, except for the escape of the /for/endetta. Try this command:

find . -type f -exec grep -q '\\/for\\/endetta' {} \; -delete 

If the exit status of grep is true, the following action is executed. Replace -delete with -print to see which files would be deleted.

like image 197
antoniob Avatar answered Oct 30 '25 13:10

antoniob


Use recursive grep to find all the files, then delete them. Like that:

for file in $( fgrep -l -r '\/for\/endetta' ../ ); do rm "$file"; done

With fgrep and single quotes you do not need to escape anything.

like image 20
user3132194 Avatar answered Oct 30 '25 13:10

user3132194



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!