简体   繁体   中英

regex in sed for search & replace (invalid reference)

I would like to replace a string in a line with shell and regex.

For example, in file configuration.php I would like to replace TO_REPLACE with OK_REPLACED :

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

\\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.

sed -i "s/^\(public \$user = *')[^']*'/\1OK_REPLACED'/g" configuration.php

If you want to replace all occurrences of TO_REPLACE , you can just do:

sed -i 's/TO_REPLACE/OK_REPLACED/g' configuration.php

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

您需要对要替换“ \\ 1”的表达式部分进行“分组”括弧:在这种情况下,第一个“'”之前的所有内容都应括起来。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM