Sara
Sara

Reputation: 2436

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?

Upvotes: 10

Views: 27615

Answers (4)

You need to quote the command's output:

echo -n "`sed  /$string/d file.txt`" > file.txt

Upvotes: 3

accuya
accuya

Reputation: 1433

sed has an in-place editing option. It's more proper to use that in your senario. e.g.

sed -i /$string/d file.txt

For the problem of your case, as the output of `` is not enclosed in double quotes, word splitting is done, by bash. And the newlines are removed. To use echo in this case, do it like this:

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

Upvotes: 2

Steve
Steve

Reputation: 54512

You do not need the echo wrap, simply try:

sed -i '/a/d' file.txt

Upvotes: 7

Thor
Thor

Reputation: 47189

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.

Upvotes: 20

Related Questions