Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

bash - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...