Search code examples
filesedline

bash delete a line from a file, permanently


I have the following code for finding a string in a file then delete the line which contains that string.

echo `sed  /$string/d  file.txt` > file.txt

the problem is that if initially file.txt contains:

a
b
c

after deleting "a" (string=a) file.txt will become

b c

instead of

b
c

can any one help me?


Solution

  • This is because of the backticks. Do this instead:

    sed -i /$string/d  file.txt
    

    Note, if you want to do this in-place, you need to use -i to sed as > will destroy the file before sed can read it.