Removing of specific line in text file

前端 未结 2 1801
北海茫月
北海茫月 2021-01-20 02:22

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

相关标签:
2条回答
  • 2021-01-20 02:59

    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
    }
    
    0 讨论(0)
  • 2021-01-20 03:02

    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.

    0 讨论(0)
提交回复
热议问题