Delete recursively lines from files that match a given string

This is just a small snipplet to remind me of how to delete lines recursively that match a string needle

#!/bin/sh
grep -rl "needle" . |
while read filename
do
(
echo $filename
sed '/needle/d' $filename> $filename.xx
mv $filename.xx $filename
)
done

References used:
www.mehtanirav.com
www.cs.mcgill.ca

  1. That seems like an awful lot of code for what sed does out-of-the-box.


    #!/bin/sh

    sed /$2/d $1 > $1.xx && mv $1.xx $1


    ./rdel.sh file_to_process needle

  2. Thanks, Chris! Your snippet is very sexy :)

  3. If you are using a real text editor, you can do it with one command without leaving to shell. :)

    :g/pattern/d

    As per this link:

    http://vim.wikia.com/wiki/Delete_all_lines_containing_a_pattern

  4. Leonid, the problem was to process many files at the same time. One of the hosting accounts was compromised by a virus on one (or more?) of the client’s computers that appended a malicious JavaScript to all PHP/HTML files

    Thanks for the tip though!

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">