drazkus
drazkus

Reputation: 11

search and replace a string after a match

I have a file that contains :

String url = "https://url_address/v2.0/vpc/peerings?name=change_variable"

I try to change the string change_variable with something else like

String url = "https://url_adress/v2.0/vpc/peerings?name=florian-testpeering-5"

But when I use :

sed 's/"https:\/\/url_adress\/v2.0\/vpc\/peerings?name/"https:\/\/url_adress\/v2.0\/vpc\/peerings?name=florian-testpeering-5"/'g

I Obtain :

String url = "https://url_adress/v2.0/vpc/peerings?name=florian-testpeering-5"=change_url"

What I did wrong ?

Edit :

To be more precise, I need to change the change_variable inside with a $peering who I declare before in my script.

Upvotes: 1

Views: 72

Answers (3)

David C. Rankin
David C. Rankin

Reputation: 84521

If I understand your edit, and you are saying you have your string in a variable at the beginning of your script, similar to:

var='String url = "https://url_address/v2.0/vpc/peerings?name=change_variable"'

and you need to change the contents of the string replacing from name=... to the end with a new value, you can simply use bash parameter expansion with substring replacement, e.g.

var="${var/name=*/name=florian-testpeering-5\"}"

Now the variable var will contain:

String url = "https://url_address/v2.0/vpc/peerings?name=florian-testpeering-5"

You can do the same thing if the string you want to replace with is also stored in another variable, such as repl="lorian-testpeering-5", in that case your substring replacement would be:

var="${var/name=*/name=${repl}\"}"

(same result in var)

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203129

Is this what you're trying to do?

awk 'index($0,"https://url_address/v2.0/vpc/peerings?name=change_variable") { sub(/change_variable/,"florian-testpeering-5") } 1' file
String url = "https://url_address/v2.0/vpc/peerings?name=florian-testpeering-5"

Upvotes: 0

Raman Sailopal
Raman Sailopal

Reputation: 12867

The fact that you have forward slashes in the url, means that is better to use another character for the sed separator and so:

sed 's@String url = "https://url_address/v2.0/vpc/peerings?name=change_variable"@String url = "https://url_address/v2.0/vpc/peerings?name=florian-testpeering-5"@g'

The normal / has been changed for @, allowing for easier reading and processing of the url.

Upvotes: 1

Related Questions