I have a line I want to replace such as
'baseurl' => 'https://231.231.231.231'
But I only want it to replace the https://231.231.231.231 part.
Basically I want it to be
'baseurl' => 'myvaluehere'
I have tried sudo sed -i "s|'baseurl'|${value1}|g" file.php
How do I replace after certain characters after 'baseurl' is matched?
CodePudding user response:
Using sed
$ sed -E "/(baseurl'[^']*')[^']*/s//\1myvaluehere/" input_file
'baseurl' => 'myvaluehere'
CodePudding user response:
Here is the way you can achieve it:
- find the match
- exclude it
- find the next pattern and replace it
And here is a perl version since have not used sed
so much:
perl -lpe "s/'baseurl' => \K'http[^ ] /'XYZ'/g" <<< "'baseurl' => 'https://231.231.231.231'"
'baseurl' => 'XYZ'
'baseurl' => \
find the match\K
exclude it (= ignore it for substitution)'http[^ ]
match this part and replace it -- the assumption is that there is no space in the url'XYZ'
<<<
is a bash feature and means String Here which provides input forperl
, or:echo "string" | perl -lpe ...
, also can beperl -lne ... file.txt
Since we use double quotes "
in perl we can use variables as well:
VAR=XXYYZZ
perl -lpe "s/'baseurl' => \K'http[^ ] /$VAR'/g" <<< "'baseurl' => 'https://231.231.231.231'"
'baseurl' => XXYYZZ'