Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a line in sed if not match is found [duplicate]

I need to add the following line to the end of a config file:

include "/configs/projectname.conf" 

to a file called lighttpd.conf

I am looking into using sed to do this, but I can't work out how.

How would I only insert it if the line doesn't already exist?

like image 544
Benjamin Dell Avatar asked Aug 24 '10 13:08

Benjamin Dell


People also ask

How do you add a new line in sed?

The sed command can add a new line after a pattern match is found. The "a" command to sed tells it to add a new line after a match is found. The sed command can add a new line before a pattern match is found. The "i" command to sed tells it to add a new line before a match is found.

How do you use sed on a specific line?

Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.


Video Answer


2 Answers

Just keep it simple :)

grep + echo should suffice:

grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar 
  • -q be quiet
  • -x match the whole line
  • -F pattern is a plain string
  • https://linux.die.net/man/1/grep

Edit: incorporated @cerin and @thijs-wouters suggestions.

like image 130
drAlberT Avatar answered Oct 13 '22 23:10

drAlberT


Try this:

grep -q '^option' file && sed -i 's/^option.*/option=value/' file || echo 'option=value' >> file 
like image 23
kev Avatar answered Oct 13 '22 23:10

kev