Home > other >  How to use regex to find and replace a specific text?
How to use regex to find and replace a specific text?

Time:07-26

I have the following code to replace the value between "-sav" and "test"

test="-val https://www.randomurl.com -sav 1aFAd381cCCb86FD300e7a3A399a6014.test -speed 2 -save -delay 14"

test=$(sed 's/-sav *.*\./-sav 12345./g' <<< $test)

echo $test

# -val https://www.randomurl.com -sav 12345.test -speed 2 -save -delay 14

How do I also include what is before -speed 2. Expected new variable value could be.

test="-val https://www.randomurl.com -sav 12345.itWorks -speed 2 -save -delay 14"

CodePudding user response:

With your shown samples, please try following sed code. Have applied -E flag to enable ERE(extended regular expression) with sed program here and where test is OP's mentioned shell variable.

echo "$test" | sed -E 's/(^-.*sav )[^.]*\.[^ ]*(.*)/-sav (\1 12345.itworks\2)/g'

Explanation: Simple explanation would be, passing echo command's output as standard input to sed command. In sed program using regex (^-.*sav )[^.]*\.[^ ]*(.*), which creates 2 capturing groups in matching regex portion and then while substituting it using these 2 capturing groups(1st and 2nd one) along with newly required value 12355 as per OP's requirement.

NOTE: I am using g flag here with sed to perform substitution Globally in case you have only 1 match in your variable then remove it.

  • Related