LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   delete file that match the content (https://www.linuxquestions.org/questions/programming-9/delete-file-that-match-the-content-542822/)

packets 04-02-2007 09:07 PM

delete file that match the content
 
Greetings!

I have a dir with 10,000 text files and growing. Do you have a script where if the word "LINUXFORUMS" has on the body of the text file, it will automatically delete the file. I cannot get to it since I'm only familiar to BASH. Anyone have a script similar to this or any ideas how can i do this? Any links where it can direct me to this kind of script?

TIA

--linux newbie

gilead 04-02-2007 10:13 PM

A very basic version to do this would be:
Code:

#!/bin/sh
#
# Example rm-files.sh - deletes all of the files in the directory it is run
# from that contain the string LINUXFORUMS
#

for i in *; do
  if grep 'LINUXFORUMS' $i >/dev/null ; then
    rm -v $i
  fi
done

You could save this in ~/bin and use it by changing to the directory containing the files and running it as ~/bin/rm-files.sh. It should have the search string passed in as a parameter and it should have some sanity checking - do you really want it deleting all matching files if you mis-typed the search string? etc, etc...

Have a look at the Advanced Bash Scripting Guide - it's well worth a read.

macemoneta 04-02-2007 10:16 PM

You don't really need a script:

Code:

grep -l "LINUXFORUMS" /someDirectory/* | awk '{print "rm -f \""$0"\""}' | bash

bigearsbilly 04-03-2007 02:23 AM

or

grep -l blah | xargs -n19 rm

packets 04-03-2007 02:27 AM

This is the one that fit the most but i will also the others. Thanks for all those who help

Quote:

grep -l blah | xargs -n19 rm

macemoneta 04-03-2007 02:47 PM

If you are going to use xargs, you probably want:

Code:

grep -Z -l "LINUXFORUMS" /someDirectory/* | xargs -0 rm -f
Otherwise, embedded blanks and other special characters won't be handled properly.


All times are GMT -5. The time now is 11:27 PM.