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

后端 未结 10 1212
深忆病人
深忆病人 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:24

    another sed solution is to always append it on the last line and delete a pre existing one.

    sed -e '$a\' -e '<your-entry>' -e "/<your-entry-properly-escaped>/d"
    

    "properly-escaped" means to put a regex that matches your entry, i.e. to escape all regex controls from your actual entry, i.e. to put a backslash in front of ^$/*?+().

    this might fail on the last line of your file or if there's no dangling newline, I'm not sure, but that could be dealt with by some nifty branching...

    0 讨论(0)
  • 2020-11-30 17:33

    This would be a clean, readable and reusable solution using grep and echo to add a line to a file only if it doesn't already exist:

    LINE='include "/configs/projectname.conf"'
    FILE='lighttpd.conf'
    grep -qF -- "$LINE" "$FILE" || echo "$LINE" >> "$FILE"
    

    If you need to match the whole line use grep -xqF

    Add -s to ignore errors when the file does not exist, creating a new file with just that line.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 17:34

    If writing to a protected file, @drAlberT and @rubo77 's answers might not work for you since one can't sudo >>. A similarly simple solution, then, would be to use tee --append (or, on MacOS, tee -a):

    LINE='include "/configs/projectname.conf"'
    FILE=lighttpd.conf
    grep -qF "$LINE" "$FILE"  || echo "$LINE" | sudo tee --append "$FILE"
    
    0 讨论(0)
提交回复
热议问题