我需要在配置文件的末尾添加以下一行:
include "/configs/projectname.conf"
到一个名为lighttpd.conf的文件
我正在研究使用sed来做到这一点,但我不知道如何。
我怎么能只插入它,如果行已经不存在?
我需要在配置文件的末尾添加以下一行:
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中的命令对管道中的第二个命令无效之前设置环境变量)
其他回答
如果您想在Linux终端中使用python脚本运行此命令…
import os,sys
LINE = 'include '+ <insert_line_STRING>
FILE = <insert_file_path_STRING>
os.system('grep -qxF $"'+LINE+'" '+FILE+' || echo $"'+LINE+'" >> '+FILE)
$和双重报价让我陷入了困境,但这奏效了。 谢谢大家
保持简单就好:)
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的建议。
几乎所有的答案都有效,但根据我的经验,并不是在所有场景或操作系统中都有效。以下是唯一适用于旧系统和新的不同口味的操作系统的东西。 我需要附加KUBECONFIG路径到bashrc文件,如果它不存在。我所做的是
我假设它存在,然后删除它。 使用sed附加我想要的字符串。
sed -i '/KUBECONFIG=/d' ~/.bashrc
echo 'export KUBECONFIG=/etc/rancher/rke2/rke2.yaml' >> ~/.bashrc
使用sed,你可以这样说:
sed -e '/option=/{s/.*/option=value/;:a;n;:ba;q}' -e 'aoption=value' filename
如果参数存在,这将替换它,否则将把它添加到文件的底部。
如果你想就地编辑文件,使用-i选项:
sed -i -e '/option=/{s/.*/option=value/;:a;n;:ba;q}' -e 'aoption=value' filename
你可以使用这个函数来查找和搜索配置更改:
#!/bin/bash
#Find and Replace config values
find_and_replace_config () {
file=$1
var=$2
new_value=$3
awk -v var="$var" -v new_val="$new_value" 'BEGIN{FS=OFS="="}match($1, "^\\s*" var "\\s*") {$2=" " new_val}1' "$file" > output.tmp && sudo mv output.tmp $file
}
find_and_replace_config /etc/php5/apache2/php.ini max_execution_time 60