用 bash / perl 替换一行的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9353602/
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
Replacing a part of a line with bash / perl
提问by Mr. King
I'm a noob at bash need to replace the mypasswordpart of this line in a file
我是 bash 的菜鸟,需要替换mypassword文件中这一行的部分
"rpc-password": mypassword
with mynewpassword
和 mynewpassword
I tried
我试过
perl -pi -e "s,PASSWORD,${password},g" "${user_conf}"
but it dosen't seem to do anything :( I can use anything that will work inside a bash script, it dosen't have to be bash or perl.
但它似乎没有做任何事情:(我可以使用任何可以在 bash 脚本中工作的东西,它不必是 bash 或 perl。
回答by ouah
perl -pi -e 's/mypassword/mynewpassword/g' file
will work
将工作
回答by TLP
Using a loose regex without keeping backups is a bad idea. Especially if you intend to use dynamic replacement strings. While it may work just fine for something like "mypassword", it will break if someone tries to replace with the password "ass"with "butt":
使用松散的正则表达式而不保留备份是一个坏主意。特别是如果您打算使用动态替换字符串。虽然它可能工作得很好,这样的事情"mypassword",这将打破,如果有人试图用密码替换"ass"有"butt":
"rpc-password": mypassword
Would become:
会成为:
"rpc-pbuttword": butt
The more automation you seek, the more strict you need the regex to be, IMO.
您寻求的自动化程度越高,您对正则表达式的要求就越严格,IMO。
I would anchor the replacement part to the particular configuration line that you seek:
我会将替换部分锚定到您寻求的特定配置行:
s/^\s*"rpc-password":\s*\K\Q$mypassword\E\s*$/$mynewpassword/
No /gmodifier, unless you intend to replace a password several times on the same line. \Kwill preserve the characters before it. Using \s*liberally will be a safeguard against user-edited configuration files where extra whitespace might have been added.
没有/g修饰符,除非您打算在同一行上多次替换密码。\K将保留它之前的字符。\s*自由使用将防止用户编辑的配置文件可能添加了额外的空格。
Also, importantly, you need to quote meta characters in the password. Otherwise a password such as t(foo)?Will also match a single t. In general, it will cause strange mismatches. This is why I added \Q...\E(see perldoc perlre) to the regex, which will allow variable interpolation, but escape meta characters.
此外,重要的是,您需要在密码中引用元字符。否则像这样的密码t(foo)?也会匹配单个t. 一般来说,它会导致奇怪的错配。这就是为什么我在正则表达式中添加\Q...\E(参见perldoc perlre),这将允许变量插值,但转义元字符。
回答by Bill
You can also use sed for this:
您也可以为此使用 sed:
sed -i 's/mypassword/mynewpassword/g' file

