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

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

    use awk

    awk 'FNR==NR && /configs.*projectname\.conf/{f=1;next}f==0;END{ if(!f) { print "your line"}} ' file file
    
    0 讨论(0)
  • 2020-11-30 17:13

    I needed to edit a file with restricted write permissions so needed sudo. working from ghostdog74's answer and using a temp file:

    awk 'FNR==NR && /configs.*projectname\.conf/{f=1;next}f==0;END{ if(!f) { print "your line"}} ' file > /tmp/file
    sudo mv /tmp/file file
    
    0 讨论(0)
  • 2020-11-30 17:15

    If, one day, someone else have to deal with this code as "legacy code", then that person will be grateful if you write a less exoteric code, such as

    grep -q -F 'include "/configs/projectname.conf"' lighttpd.conf
    if [ $? -ne 0 ]; then
      echo 'include "/configs/projectname.conf"' >> lighttpd.conf
    fi
    
    0 讨论(0)
  • 2020-11-30 17:16

    The answers using grep are wrong. You need to add an -x option to match the entire line otherwise lines like #text to add will still match when looking to add exactly text to add.

    So the correct solution is something like:

    grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar
    
    0 讨论(0)
  • 2020-11-30 17:22

    Using sed: It will insert at the end of line. You can also pass in variables as usual of course.

    grep -qxF "port=9033" $light.conf
    if [ $? -ne 0 ]; then
      sed -i "$ a port=9033" $light.conf
    else
        echo "port=9033 already added"
    fi
    

    Using oneliner sed

    grep -qxF "port=9033" $lightconf || sed -i "$ a port=9033" $lightconf
    

    Using echo may not work under root, but will work like this. But it will not let you automate things if you are looking to do it since it might ask for password.

    I had a problem when I was trying to edit from the root for a particular user. Just adding the $username before was a fix for me.

    grep -qxF "port=9033" light.conf
    if [ $? -ne 0 ]; then
      sudo -u $user_name echo "port=9033" >> light.conf
    else
        echo "already there"    
    fi
    
    0 讨论(0)
  • 2020-11-30 17:23

    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
    
    0 讨论(0)
提交回复
热议问题