0

Although this seems like a simple task, the sed call is not substituting the value that I send for IP. Instead, it is replacing localhost with "${IP}".

substitute() {
    export IP=$1
    echo $IP
    LC_ALL=C find . -type f -name '*.txt' -exec sed -i.bak 's/localhost/"${IP}"/g' {} \;
}

substitute 10.20.30.40

How do I achieve my purpose of substituting with a value send from an argument?

1

Your single quotes are preventing the ${IP} from being interpolated into the value. bash -x would help (i.e. add -x to a shebang of #!/bin/bash in the script)

    + substitute 10.20.30.40
+ export IP=10.20.30.40
+ IP=10.20.30.40
+ echo 10.20.30.40
10.20.30.40
+ LC_ALL=C
+ find /tmp -type f -name '*.txt' -exec sed -i.bak 's/localhost/"${IP}"/g' '{}' ';'

if you swap them,

   + substitute 10.20.30.40
+ export IP=10.20.30.40
+ IP=10.20.30.40
+ echo 10.20.30.40
10.20.30.40
+ LC_ALL=C
+ find /tmp -type f -name '*.txt' -exec sed -i.bak 's/localhost/'\''10.20.30.40'\''/g' '{}' ';'

the interpolation works. Not sure want quotes in there in the end but ...

  • Thank you!. That was it. I don't know why the single quotes caused any problem. – Senthil Kumaran May 11 '16 at 20:09

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