views:

52

answers:

3

Hi 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 cant work out how to only insert it if the line doesnt already exist. Is anyone able to enlighten me?

Thanks in advance,

Ben

A: 

Just keep it simple :)

grep + echo should suffice:

grep -q 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar
AlberT
This one does the reverse of what I need. It only adds the line to the file IF the line already exists. I only want to add it if it doesnt exist. Any ideas?
Benjamin Dell
AlberT
I would add the -q switch to grep to suppress output: `grep -vq ...`
Dave Kirby
good improvement :)
AlberT
bPizzi
Thanks guys, but this command still continues to add a brand new line if that line already exists. It should only write one if it doesnt exist. For testing i have been running:grep -vq 'include "/configs/projectname.conf"' text.txt || echo 'include "/configs/projectname.conf"' >> text.txt
Benjamin Dell
OK i've only managed to get it work by doing this:grep 'include "/configs/projectname.conf"' text.txt || echo 'include "/configs/projectname.conf"' >> text.txt
Benjamin Dell
A: 

use awk

awk 'FNR==NR && /configs.*projectname\.conf/{f=1;next}f==0;END{ if(!f) { print "your line"}} ' file file
ghostdog74
I cant get this one to work for some reason :(
Benjamin Dell
A: 

Here's a sed version:

sed -e '\|include "/configs/projectname.conf"|h; ${x;s/incl//;{g;t};a\' -e 'include "/configs/projectname.conf"' -e '}' file

If your string is in a variable:

string='include "/configs/projectname.conf"'
sed -e "\|$string|h; \${x;s|$string||;{g;t};a\\" -e "$string" -e "}" file
Dennis Williamson