-2

We have Bash script. We want to change the name - master02 with $machine_master in the Bash script.

    value=master02_up
    #master02
    http://master02.$domain:8080

How to change master02 to $machine_master, only if master02 is after http://master02.

Expected output:

    value=master02_up
    #master02
    http://$machine_master.$domain:8080
  • 1
    awk '/http/ {sub(/master02/,"$machine_master")}1' file – jasonwryan Jul 5 '18 at 7:48
  • 1
    is $machine_master intended as variable or as literal string? – RomanPerekhrest Jul 5 '18 at 7:59
  • @RomanPerekhrest From the expected output, it looks as if it's intended to be a fixed string. – Kusalananda Jul 5 '18 at 9:54
  • @Kusalananda, there are many unexpected cases in comprehension of user questions. I feel like it's better to obtain the real "picture" through elaboration (even if something seems simple) (based on experience of working with SO and U&L) – RomanPerekhrest Jul 5 '18 at 10:18
1

Using standard sed:

sed 's#http://master02.\$domain:8080#http://$machine_master.$domain:8080#' file >newfile

This replaces the exact string http://master02.$domain:8080 with http://$machine_master.$domain:8080 and writes the result to a new file.

The $ in $domain has to be escaped to not be interpreted as an "end of line" pattern. The $ in the replacement text does not need to be escaped as this part is not a pattern.

I'm using # as a delimiter for the sed substitute command (s) as the pattern and replacement text both contain / which is the default delimiter.

The command could also be shortened to

sed 's#http://master02#http://$machine_master#' file >newfile

if it's safe to do so (this depends on the contents of the file and what instances of text you'd like to replace).

Testing:

$ cat file
value=master02_up
#master02
http://master02.$domain:8080

$ sed 's#http://master02.\$domain:8080#http://$machine_master.$domain:8080#' file >newfile

$ cat newfile
value=master02_up
#master02
http://$machine_master.$domain:8080

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.