Removing a specific line in bash with an exact string

Viewed 114

I'm having trouble in getting sed to remove just the specific line I want. Let's say I have a file that looks like this:

testfile
testfile.txt
testfile2

Currently I'm using this to remove the line I want:

sed -i "/$1/d" file

The issue is that with this if I were to give testfile as input it would delete all three lines but I want it to only remove the first line. How do I do this?

2 Answers

With grep

grep -x -F -v -- "$1" file
# or
grep -xFv -- "$1" file

-F is for "fixed strings" -- turns off regex engine.
-x is to match entire line.
-v is for "everything but" the matched line(s).
-- to signal the end of options, in case $1 starts with a hyphen.

To save the file

grep -xFv -- "$1" file | sponge file     # `moreutils` package

# or
tmp=$(mktemp)
grep -xFv -- "$1" file > "$tmp" && mv "$tmp" file

So match the whole line.

var=testfile
sed -i '/^'"$var"'$/d' file
# or with " quoting
sed -i "/^$var\$/d" file

You can learn regex with fun online with regex crosswords.

Related