Search code examples
bashsedterminalipconfig

Using variables in sed


I'm a n00b trying to return my IP address to a variable, which is then used in the sed command within a bash script. I'm trying to replace the text 'mycomputer' in a file with my IP address without much luck.

Here are my attempts:

1

localip=`ipconfig getifaddr en0`
sed -i '' “s/mycomputer/$localip/” config.txt

The error I receive is:

sed: 1: "“s/mycomputer/192.168 ...": invalid command code ?

2

localip=`ipconfig getifaddr en0`
sed -i '' 's/mycomputer/$localip/g' config.txt

Changes 'mycomputer' to '$localip' - not the actual IP address

3

localip=`ipconfig getifaddr en0`
sed -i '' 's/mycomputer/‘“$localip”’/g’ config.txt

Error:

./mytest.sh: line 5: unexpected EOF while looking for matching `''
./mytest.sh: line 6: syntax error: unexpected end of file

Any thoughts?!?!

Edit:

This is for use in a bash script, as per below:

#!/bin/bash

cd "`dirname "$0"`"
localip=`ipconfig getifaddr en0’
sed -i '' "s/mycomputer/$localip/" config.txt

Solution

  • You got the double-quotes wrong:

    sed -i '' “s/mycomputer/$localip/” config.txt
    

    This should work (notice the difference):

    sed -i '' "s/mycomputer/$localip/" config.txt
    

    Actually you have similar problems on other lines too. So the full script, corrected:

    #!/bin/bash    
    cd $(dirname "$0")
    localip=$(ipconfig getifaddr en0)
    sed -i '' "s/mycomputer/$localip/" config.txt
    

    Note that -i '' is for the BSD version of sed (in BSD systems and MAC). In Linux, you'd write the same thing this way:

    sed -i "s/mycomputer/$localip/" config.txt