Appending a line to a file only if it does not already exist

Benjamin Dell picture Benjamin Dell · Aug 24, 2010 · Viewed 97.1k times · Source

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?

Answer

drAlberT picture drAlberT · Aug 24, 2010

Just keep it simple :)

grep + echo should suffice:

grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar

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