我需要在配置文件的末尾添加以下一行:

include "/configs/projectname.conf"

到一个名为lighttpd.conf的文件

我正在研究使用sed来做到这一点,但我不知道如何。

我怎么能只插入它,如果行已经不存在?


当前回答

为了减少重复,我通过设置变量详细阐述了kev的grep/sed解决方案。

设置第一行中的变量(提示:$_option将匹配一行中的所有内容,直到值[包括任何分隔符,如=或:])。

_file="/etc/ssmtp/ssmtp.conf" _option="mailhub=" _value="my.domain.tld" \
        sh -c '\
            grep -q "^$_option" "$_file" \
            && sed -i "s/^$_option.*/$_option$_value/" "$_file" \
            || echo "$_option$_value" >> "$_file"\
        '

注意那个sh -c '…’只是有扩大变量范围的效果,而不需要导出。(参见在bash中的命令对管道中的第二个命令无效之前设置环境变量)

其他回答

几乎所有的答案都有效,但根据我的经验,并不是在所有场景或操作系统中都有效。以下是唯一适用于旧系统和新的不同口味的操作系统的东西。 我需要附加KUBECONFIG路径到bashrc文件,如果它不存在。我所做的是

我假设它存在,然后删除它。 使用sed附加我想要的字符串。

sed -i '/KUBECONFIG=/d' ~/.bashrc

echo 'export KUBECONFIG=/etc/rancher/rke2/rke2.yaml' >> ~/.bashrc

下面是一个awk实现

/^option *=/ { 
  print "option=value"; # print this instead of the original line
  done=1;               # set a flag, that the line was found
  next                  # all done for this line
}
{print}                 # all other lines -> print them
END {                   # end of file
  if(done != 1)         # haven't found /option=/ -> add it at the end of output
    print "option=value"
}

使用

awk -f update.awk < /etc/fdm_monitor.conf > /etc/fdm_monitor.conf.tmp && \
   mv /etc/fdm_monitor.conf.tmp /etc/fdm_monitor.conf

or

awk -f update.awk < /etc/fdm_monitor.conf | sponge /etc/fdm_monitor.conf

编辑: 一句话:

awk '/^option *=/ {print "option=value";d=1;next}{print}END{if(d!=1)print "option=value"}' /etc/fdm_monitor.conf | sponge /etc/fdm_monitor.conf

下面是awk的一行代码:

 awk -v s="option=value" '/^option/{f=1;$0=s}7;END{if(!f)print s}' file

这不会对文件进行就地更改,但是您可以:

awk '...' file > tmpfile && mv tmpfile file
 sed -i 's/^option.*/option=value/g' /etc/fdm_monitor.conf
 grep -q "option=value" /etc/fdm_monitor.conf || echo "option=value" >> /etc/fdm_monitor.conf

为了减少重复,我通过设置变量详细阐述了kev的grep/sed解决方案。

设置第一行中的变量(提示:$_option将匹配一行中的所有内容,直到值[包括任何分隔符,如=或:])。

_file="/etc/ssmtp/ssmtp.conf" _option="mailhub=" _value="my.domain.tld" \
        sh -c '\
            grep -q "^$_option" "$_file" \
            && sed -i "s/^$_option.*/$_option$_value/" "$_file" \
            || echo "$_option$_value" >> "$_file"\
        '

注意那个sh -c '…’只是有扩大变量范围的效果,而不需要导出。(参见在bash中的命令对管道中的第二个命令无效之前设置环境变量)