Andres
Andres

Reputation: 275

Removing of specific line in text file

I am working on an option which will be able to remove the line specified if the user types in the exact title and author.

However I will not be able to make it work.

My function contents are shown below

fnRemoveBook()
{
echo"Title: "
read Title
echo"Author: "
read Author

if grep -Fqe "$Title:$Author" BookDB.txt; then
    sed -i '/"$Title:$Author"/ d' BookDB.txt
    echo "Book removed successfully!"
else
    echo "Error! Book does not exist!"
fi
}

The BookDB contents are shown below

Hello World:Andreas:10:5:2
Teaching:Mary Ann:50:23:5

After I have keyed in "Hello World" for title and "Andreas" for author, the program will be able to enter into the loop and echo-ed Book removed successfully.

However I checked the BookDB.txt the line has not been removed yet and I wonder why.

I hope I will be able to get some answers out here as I have been doing research on the internet but still have no answers at the moment.

Thanks in advance to those who helped! :)

Upvotes: 3

Views: 985

Answers (2)

Dan Fego
Dan Fego

Reputation: 13994

You're trying to pass a bash variable (two, actually) into a sub-program (sed), but surrounding the expression you're passing in single-quotes, which does no parameter expansion. That means that sed is literally seeing $Title:$Author. Try putting the whole sed expression in double-quotes:

sed -i "/$Title:$Author/d" BookDB.txt

This will allow bash to expand $Title and $Author before they get into sed.

Upvotes: 2

jaypal singh
jaypal singh

Reputation: 77075

Using single quotes does not interpolate variables. Try something like this -

fnRemoveBook()
{
echo "Title: "
read Title
echo "Author: "
read Author

if grep -Fqe "$Title:$Author" BookDB.txt; then
    sed -i "/$Title:$Author/ d" BookDB.txt    # <---- Changes made here
    echo "Book removed successfully!"
else
    echo "Error! Book does not exist!"
fi
}

Upvotes: 1

Related Questions