Reputation: 59
Probably a pretty straight forward one but I'm fairly new to bash I'm trying to delete a line from a .txt file that contains a specific string. The string is specified as a variable "$logline"
My code for sed is currently:
logline="example2"
sed -i "/$logline/d" > /root/file.txt
The contents of the /root/file.txt
file is...
/root/Dir/example.txt
/root/Dir2/example2.txt
/root/Dir/example3.html
...
I expect just the line /root/Dir2/example2.txt
to be deleted.
However when I run this the entire txt file is getting wiped, and I get the error message sed: no input files
.
Any idea what I'm missing here?
Thanks
Upvotes: 1
Views: 175
Reputation: 30704
If your variable $logline
contains exact text to be matched, sed is probably the wrong program to be using. Pattern addresses are regular expressions, and you'll need to escape any of the metacharacters understood in basic REs, including \
, *
and .
.
For removing a fixed string, you'll probably find it easier to use grep -Fv
; something like
grep -Fv -- "$logline" <"$file" >"$file.new"; mv "$file.new" "$file"
If you really must use sed, you should choose whether you're editing in-place with -i
or using standard output - you don't get both. So either
sed -i "/$logline/d" "$file"
sed "/$logline/d" "$file" >"$file.new" && mv "$file.new" "$file"
Upvotes: 2
Reputation: 123410
sed -i
has no output, so when you redirect to a file it will just be truncated.
Instead, give the filename to sed directly without redirecting:
sed -i "/$logline/d" /root/file.txt
Upvotes: 2