soarinblue
soarinblue

Reputation: 1687

find specific text in a directory and delete the lines from the files

I want to find specific text in a directory, and then delete the lines from the files that include the specific text.

Now I have two questions:

  1. How can I achieve the task?
  2. What is wrong with What I have tried? I have tried the methods below, but failed. the details are following:

    grep -rnw "./" -e "webdesign"

    This searches the current directory with pattern "webdesign", and I get the result:

    .//pages/index.html:1:{% load webdesign %}
    .//pages/pricing.html:1:{% load webdesign %}
    .//prototypes.py:16:        'django.contrib.webdesign',
    

    Then I use sed to remove the lines from those files, which doesn't work, only get blank file ( I mean it deletes all my file content):

    sed -i "/webdesign/d" ./pages/index.html
    or
    sed "/webdesign/d" ./pages/index.html > ./pages/index.html
    

My software environment is: OS X Yosemite, Mac Terminal, Bash

Upvotes: 0

Views: 55

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

A loop in bash will do the trick provided that there are no filenames with spaces (in which case other solutions are possible, but this is the simplest)

for i in `grep -lrnw "yourdirectory/" -e "webdesign"`
do
   sed "/webdesign/d" $i > $i.tmp
   # safety to avoid destroying the file if problem arises (disk full?)
   if [ $? = 0 ] ; then
      mv -f $i.tmp $i
   fi
done

note that you should not locate this script in the current directory because it contains webdesign and it will be modified as well :)

Thanks to choroba, I know that -i option doesn't work like wished. But it has another meaning or it would be rejected by the opt parser. It has something to do with suffixes, well, it doesn't matter now, but it's difficult to see the problem at first. Without -i you cannot work on a file in-place. And redirecting output to the input just destroys the input file (!). That's why your solution did not work.

Upvotes: 1

choroba
choroba

Reputation: 241788

You can install GNU sed that supports the -i option, then

sed -i '/webdesign/d' files

should work. Note that it's safer to use -i~ to create a backup.

You cannot write to the same file you're reading from, that's why

sed /webdesign/d file > file

doesn't work (it overwrites the file before you can read anything from it). Create a temporary file

sed /webdesign/d file > file.tmp
mv file.tmp file

Upvotes: 1

Related Questions