I would like to replace a string in a line with shell and regex.
我想用shell和regex替换一行中的字符串。
For example, in file configuration.php
I would like to replace TO_REPLACE
with OK_REPLACED
:
例如,在文件configuration.php中,我想用OK_REPLACED替换TO_REPLACE:
public $user = 'TO_REPLACE';
I tried this command:
我试过这个命令:
cd ~/public_html; sed -i "s/^\public $user = *'[^']*'/\1OK_REPLACED'/g" configuration.php
but I get this error
但是我得到了这个错误
sed: -e expression #1, char 39: invalid reference \1 on `s' command's RHS
I also tried this one but nothing
我也试过这个,但没有
sed -i "s/^\(public \$user = *')[^']*'/\1OK_REPLACED'/g" configuration.php
3 个解决方案
#1
1
\1
in the replacement is replaced with whatever matched the first capture group in the regexp, but you have no capture groups. You need to put capture groups around the parts of the original line that you want to copy into the replacement.
替换中的\ 1替换为正则表达式中与第一个捕获组匹配的任何内容,但您没有捕获组。您需要将捕获组放在要复制到替换的原始行的部分周围。
sed -i "s/^\(public \$user = *')[^']*'/\1OK_REPLACED'/g" configuration.php
If you want to replace all occurrences of TO_REPLACE
, you can just do:
如果要替换所有出现的TO_REPLACE,您可以这样做:
sed -i 's/TO_REPLACE/OK_REPLACED/g' configuration.php
#2
1
I think your parenthesis must be balanced. Your first one is prefixed with a backslash, but the 2nd one is not. Try this:
我认为你的括号必须平衡。你的第一个前缀是反斜杠,但第二个不是。尝试这个:
sed -i "s/^\(public \$user = *'\)[^']*'/\1OK_REPLACED'/g" configuration.php
or this:
或这个:
sed -r -i "s/^(public \$user = *')[^']*'/\1OK_REPLACED'/g" configuration.php
#3
0
You need to "group" put parenthesis around the piece of the expression that you need to substitute for "\1": in this case everything before the first "'".
你需要“组合”将括号括在你需要替换“\ 1”的表达式的一部分:在这种情况下,在第一个“'”之前的所有内容。
#1
1
\1
in the replacement is replaced with whatever matched the first capture group in the regexp, but you have no capture groups. You need to put capture groups around the parts of the original line that you want to copy into the replacement.
替换中的\ 1替换为正则表达式中与第一个捕获组匹配的任何内容,但您没有捕获组。您需要将捕获组放在要复制到替换的原始行的部分周围。
sed -i "s/^\(public \$user = *')[^']*'/\1OK_REPLACED'/g" configuration.php
If you want to replace all occurrences of TO_REPLACE
, you can just do:
如果要替换所有出现的TO_REPLACE,您可以这样做:
sed -i 's/TO_REPLACE/OK_REPLACED/g' configuration.php
#2
1
I think your parenthesis must be balanced. Your first one is prefixed with a backslash, but the 2nd one is not. Try this:
我认为你的括号必须平衡。你的第一个前缀是反斜杠,但第二个不是。尝试这个:
sed -i "s/^\(public \$user = *'\)[^']*'/\1OK_REPLACED'/g" configuration.php
or this:
或这个:
sed -r -i "s/^(public \$user = *')[^']*'/\1OK_REPLACED'/g" configuration.php
#3
0
You need to "group" put parenthesis around the piece of the expression that you need to substitute for "\1": in this case everything before the first "'".
你需要“组合”将括号括在你需要替换“\ 1”的表达式的一部分:在这种情况下,在第一个“'”之前的所有内容。