bash 使用 sed 修改 key="Value" 配置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8134673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Modify key="Value" config with sed
提问by SebastianK
I am trying to write a script that configures a config file used by a nother script. I am trying to use sed like this
我正在尝试编写一个脚本来配置另一个脚本使用的配置文件。我正在尝试像这样使用 sed
sed -c -i "s/\($TARGET_KEY *= *\).*/$REPLACEMENT_VALUE/" $CONFIG_FILE
But it's not working as it is intended to it strips the quotation marks and i cant figure out how to write it so it dont.
但它不起作用,因为它旨在去除引号,我无法弄清楚如何编写它所以它不会。
the second problem is that when i run this on Mac OS the out put is an error:
第二个问题是,当我在 Mac OS 上运行它时,输出是一个错误:
sed: illegal option -- c
usage: sed script [-Ealn] [-i extension] [file ...]
sed [-Ealn] [-i extension] [-e script] ... [-f script_file] ... [file ...]
I am new to usage of sed so please forgive my lack of skills in this area.
我是 sed 的新手,所以请原谅我在这方面缺乏技能。
采纳答案by Kent
see the test below, I didn't add "-i", just print the output. you can add -i if you need:
看下面的测试,我没有加“-i”,只是打印输出。如果需要,您可以添加 -i:
kent$ cat c.conf
key1="value1"
foo = "fooValue"
bar="barValue"
kent$ echo $k1
foo
kent$ echo $v1
foo_new
kent$ sed -r "s/($k1 *= *\").*/$v1\"/" c.conf
key1="value1"
foo = "foo_new"
bar="barValue"
回答by OpenSauce
Have you tried escaping the quotes? This works for me (on Cygwin):
你有没有试过转义引号?这对我有用(在 Cygwin 上):
~$ echo -e "key1=\"value1\"\nkey2=\"value2\""
key1="value1"
key2="value2"
~$ TARGET_KEY=key2
~$ REPLACEMENT_VALUE=new_val
~$ echo -e "key1=\"value1\"\nkey2=\"value2\"" | sed "s/\($TARGET_KEY *= *\"\).*/$REPLACEMENT_VALUE\"/"
key1="value1"
key2="new_val"
~$

