Benjamin Dell Benjamin Dell - 3 months ago 15
Linux Question

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

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

Just keep it simple :)

grep + echo should suffice:

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

Edit: incorporated @Cerin suggestion.

NOTE: for "editors" changing my answer: if you have an alternative solution give your own answer! Editing is intended for clarifying, formatting, better English and so on! Don't change the answer given by others! (thank you)

Comments