Home > Software engineering >  How to replace certain position after match using sed in Ubuntu?
How to replace certain position after match using sed in Ubuntu?

Time:07-26

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:

  1. find the match
  2. exclude it
  3. find the next pattern and replace it

And here is a 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 feature and means String Here which provides input for perl , or:
    • echo "string" | perl -lpe ..., also can be
    • perl -lne ... file.txt

Since we use double quotes " in we can use variables as well:

VAR=XXYYZZ
perl -lpe "s/'baseurl' => \K'http[^ ] /$VAR'/g" <<< "'baseurl' => 'https://231.231.231.231'"
'baseurl' => XXYYZZ'
  • Related