Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove line containing a specific string from file?

Tags:

string

bash

sed

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
like image 688
Jared Aaron Loo Avatar asked Dec 25 '22 07:12

Jared Aaron Loo


1 Answers

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.
like image 57
fedorqui 'SO stop harming' Avatar answered Mar 08 '23 11:03

fedorqui 'SO stop harming'