我需要在配置文件的末尾添加以下一行:
include "/configs/projectname.conf"
到一个名为lighttpd.conf的文件
我正在研究使用sed来做到这一点,但我不知道如何。
我怎么能只插入它,如果行已经不存在?
我需要在配置文件的末尾添加以下一行:
include "/configs/projectname.conf"
到一个名为lighttpd.conf的文件
我正在研究使用sed来做到这一点,但我不知道如何。
我怎么能只插入它,如果行已经不存在?
当前回答
只使用sed,我建议使用以下解决方案:
sed -i \
-e 's#^include "/configs/projectname.conf"#include "/configs/projectname.conf"#' \
-e t \
-e '$ainclude "/configs/projectname.conf"' lighttpd.conf
将include“/configs/projectname.conf”行替换为自身(此处使用#作为分隔符)
T如果替换成功,跳过其余命令
$a否则跳转到最后一行,并在其后添加include "/configs/projectname.conf "
其他回答
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
保持简单就好:)
Grep + echo就足够了:
grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar
-q安静点 -x匹配整行 -F pattern是一个普通字符串 https://linux.die.net/man/1/grep
编辑: 合并了@cerin和@thijs-wouters的建议。
sed -i '1 h
1 !H
$ {
x
s/^option.*/option=value/g
t
s/$/\
option=value/
}' /etc/fdm_monitor.conf
加载缓冲区中的所有文件,在结束时,更改所有发生的情况,如果没有发生变化,则添加到结束
我需要编辑一个文件限制写权限,所以需要sudo。从ghostdog74的答案工作,并使用一个临时文件:
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
使用awk
awk 'FNR==NR && /configs.*projectname\.conf/{f=1;next}f==0;END{ if(!f) { print "your line"}} ' file file