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

后端 未结 10 1228
深忆病人
深忆病人 2020-11-30 16:44

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

include \"/configs/projectname.conf\"

to a file called lighttpd.conf

10条回答
  •  情话喂你
    2020-11-30 17:34

    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.

提交回复
热议问题