Reputation: 2436
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
Reputation: 94
You need to quote the command's output:
echo -n "`sed /$string/d file.txt`" > file.txt
Upvotes: 3
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
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