追加或使用SED / bash的单行修改conf文件键 [英] Append or modify keys in conf files using sed/bash one-liner
问题描述
我经常要修改的文件,如 sysctl.conf的
,我很熟悉使用SED替换现有的值。
I often have to modify files such as sysctl.conf
, and I'm familiar with using sed to replace existing values.
有没有办法来追加新的键/值对,如果sed的文件是不能够替代它?
Is there a way to append the new key/value pair to the file if sed wasn't able to replace it?
例如,使用下面的例子:使用bash脚本修改配置文件
For instance, using this example: modify config file using bash script
sed -c -i "s/\($TARGET_KEY *= *\).*/\1$REPLACEMENT_VALUE/" $CONFIG_FILE
我怎么可以在 $ TARGET_KEY = $ REPLACEMENT_VALUE
新行添加到 $ CONFIG_FILE
使用相同的SED前$略有变化p $ pssion?
How could I add the $TARGET_KEY = $REPLACEMENT_VALUE
new line to $CONFIG_FILE
using the same sed expression with slight changes?
和一个相关主题,我怎么能强迫 $ CONFIG_FILE
的创作,如果不存在呢?
And on a related topic, how can I force creation of $CONFIG_FILE
if it didn't exist?
推荐答案
您不能很容易地做到这一切在一个单一的 SED
电话。这可能是最简单的,使其两个步骤:
You can't easily do it all in a single sed
call. It's probably simplest to make it two steps:
if grep -q "$TARGET_KEY *= " $CONFIG_FILE; then
sed -c -i "s/\($TARGET_KEY *= *\).*/\1$REPLACEMENT_VALUE/" $CONFIG_FILE
else
echo "$TARGET_KEY = $REPLACEMENT_VALUE" >>$CONFIG_FILE
fi
有几件事情你应该做的,使上面的更强劲,但是:
There are a few things you should probably do to make the above more robust, however:
-
您定期的前pression不固定,这意味着试图设置端口也将查找/更改支持等。
Your regular expression is not anchored, which means that trying to set 'PORT' will also find/change 'SUPPORT', etc.
这将不匹配,如果配置文件可能有标签以及空格
It won't match if the config file might have tabs as well as spaces
它失败如果更换价值有斜杠。
It fails if the replacement value has slashes in it.
您应该始终报价参数扩展,比如 $ CONFIG_FILE
,如果文件路径中包含空格或shell元字符。
You should always quote parameter expansions like $CONFIG_FILE
, in case the file path contains spaces or shell metacharacters.
这是安全的。这种情况下,但可能混淆当你想要一个反斜杠使用单反斜杠在双引号字符串。壳留给他们独处的时候它不承认后,随之而来的特殊序列,但如果你一倍他们来说,这会更清晰。
It's safe in this instance, but potentially confusing to use single backslashes in a double-quoted string when you want a literal backslash. The shell leaves them alone when it doesn't recognize what comes after it as a special sequence, but it would be clearer if you doubled them.
这是什么 -c
做你的sed的版本?无论是我的Linux和Mac版支持这样一种选择。
What does -c
do on your version of sed? Neither my Linux nor Mac versions support such an option.
所以,我会做这样(的 ^ I
的再present文字制表符,并在 ^ A
的字面控制-A字符,例如通过在命令行中键入第一控制-V)输入:
So I would do it this way (the ^I
's represent literal tab characters, and the ^A
's literal control-A characters, entered by for example typing control-V first on the command line):
if grep -q "^[ ^I]*$TARGET_KEY[ ^I]*=" "$CONFIG_FILE"; then
sed -i -e "s^A^\\([ ^I]*$TARGET_KEY[ ^I]*=[ ^I]*\\).*$^A\\1$REPLACEMENT_VALUE^A" "$CONFIG_FILE"
else
echo "$TARGET_KEY = $REPLACEMENT_VALUE" >> "$CONFIG_FILE"
fi
这篇关于追加或使用SED / bash的单行修改conf文件键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!