Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash delete a line from a file, permanently

Tags:

file

sed

line

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?

like image 668
Sara Avatar asked Dec 04 '22 15:12

Sara


1 Answers

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.

like image 149
Thor Avatar answered Dec 07 '22 05:12

Thor