2

I have a script that contains a few variables. One of them is some proprietary path MYPATH.
I want to save the output of MYPATH and then replace another variable SOME_OTHER_PATH with the same value.

Current entry in myfile.sh

MYPATH="/opt/local/custom/myfiles"
SOME_OTHER_PATH=""

Output that I want

MYPATH="/opt/local/custom/myfiles"
SOME_OTHER_PATH="/opt/local/custom/myfiles"

The script that I wrote does this

mylocalpath=`sed -n /^MYPATH/p' myfile.sh | sed -e 's/MYPATH/'`
sed -i -e "s/^SOME_OTHER_PATH/${mylocalpath}" myfile.sh

There are two problems here

  1. Since ${mylocalpath} contains "/", sed tries to evaluate these and throws an exception
  2. I would like to bundle the entire script in a sed file (instead of running sed twice) and execute it as

    sed -f sed_file myfile.sh
    
souser
  • 5,868
  • 5
  • 35
  • 50
  • For problem #1, see [this answer regarding escaping characters for sed](http://stackoverflow.com/a/29613573/2877364) – cxw May 31 '16 at 16:25

1 Answers1

2

While I'm sure that this is possible with sed, I would recommend using awk:

awk -F'"' '/^MYPATH=/ { path = $2 } /^SOME_OTHER_PATH=/ { $0 = $1 path "\"" } 1' file

Save the path to a variable when the line starts with MYPATH and use it when the line starts with SOME_OTHER_PATH. The 1 at the end is the shortest true condition and { print } is the default action, so every line is printed.

To perform an "in-place" edit, just use a temp file:

awk ... file > tmp && mv tmp file
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141