Jared Aaron Loo
Jared Aaron Loo

Reputation: 678

How to remove line containing a specific string from file?

I have a file BookDB.txt which stores information in the following manner :

C++ for dummies:Jared:10.67:4:5
Java for dummies:David:10.45:3:6 
PHP for dummies:Sarah:10.47:2:7

Assuming that during runtime, the scipt asks the user for the title he wants to delete. This is then stored in the TITLE variable. How do I then delete the line containing the string in question? I've tried the following command but to no avail :

sed '/$TITLE/' BookDB.txt >> /dev/null

Upvotes: 5

Views: 16814

Answers (2)

fedorqui
fedorqui

Reputation: 289505

You can for example do:

$ title="C++ for dummies"
$ sed -i "/$title/d" a
$ cat a
**Java for dummies**:David:10.45:3:6
**PHP for dummies**:Sarah:10.47:2:7

Note few things:

  • Double quotes in sed are needed to have you variable expanded. Otherwise, it will look for the fixed string "$title".
  • With -i you make in-place replacement, so that your file gets updated once sed has performed.
  • d is the way to indicate sed that you want to delete such matching line.

Upvotes: 9

Avinash Raj
Avinash Raj

Reputation: 174696

Your command should be,

sed "/$TITLE/d" file

To save the changes, you need to add -i inline edit parameter.

sed -i "/$TITLE/d" file

For variable expansion in sed, you need to put the code inside double quotes.

Upvotes: 4

Related Questions