[英]Linux Bash Sed one liner change config value - with space or no space
I need a Sed one liner to change a key = value
pair in a config file, respecting the space or even no space between key
and =
我需要一个 Sed one liner 来更改配置文件中的
key = value
对,尊重空格,甚至key
和=
之间没有空格
// config_file could look like this
key = oldValue
key=oldValue
key= oldValue
key =oldValue
keyABC = doNotMatchThis
What I got so far is this到目前为止我得到的是这个
sed -i '/key/s/= .*/= newValue/' config_file
The result will be结果将是
key = newValue
key=oldValue
key= newValue
key =oldValue
keyABC = newValue
keyABC
changed also (very bad!). keyABC
也改变了(非常糟糕!)。 How can I achieve this?我怎样才能做到这一点?
What I want is我想要的是
key = newValue
key=newValue
key= newValue
key =newValue
keyABC = doNotMatchThis
You may use您可以使用
sed -i '/^key *=/s/=.*/= newValue/' config_file
The line qualitifier pattern is ^key *=
:行限定符模式是
^key *=
:
^
- start of string ^
- 字符串的开始key
- a key
string key
- 一个key
字符串*=
- 0 or more spaces and then =
. *=
- 0 个或多个空格,然后是=
。 The substitution command is s/=.*/= newValue/
: it finds =
and any 0+ chars after, and replaces with = newValue
.替换命令是
s/=.*/= newValue/
:它找到=
和后面的任何 0+ 字符,并用= newValue
替换。
See the online sed
demo .请参阅在线
sed
演示。
s="key = oldValue
key=oldValue
key= oldValue
key =oldValue
keyABC = doNotMatchThis"
sed '/^key *=/s/=.*/= newValue/' <<< "$s"
Output:输出:
key = newValue
key= newValue
key= newValue
key = newValue
keyABC = doNotMatchThis
With GNU sed.用 GNU sed。
sed -i -r 's/^(key *= *).*/\1newValue/' file
Output:输出:
key = newValue key=newValue key= newValue key =newValue keyABC = doNotMatchThis
sed -i 's/\(key[[:space:]]\{0,1\}=[[:space:]]\{0,1\}\).*/\1 newValue/g' file
In case you want to match both tabs and spaces, use this instead:如果您想同时匹配制表符和空格,请改用:
sed -i 's/\(key[[:blank:]]\{0,1\}=[[:blank:]]\{0,1\}\).*/\1 newValue/g' file
Also to limit the number of occurences of those spaces, change limits in \\{0,1\\}
and in case you accept any number of spaces,还要限制这些空格的出现次数,请更改
\\{0,1\\}
限制,如果您接受任意数量的空格,
sed -i 's/\(key[[:blank:]]*=[[:blank:]]*\).*/\1 newValue/g' file
Also, the same can be done with a little more simplicity with awk
(well I think so):此外,使用
awk
可以更简单地完成相同的操作(我认为是这样):
newVal="your_new_value"
awk -F= -v newVal="$newVal" '/ *key *=/{$2="="newVal}{print}' file
To retain changes in file:要保留文件中的更改:
newVal="your_new_value"
gawk -i -F= -v newVal="$newVal" '/ *key *=/{$2="="newVal}{print}' file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.