Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...