Using variables in sed

1.9k views Asked by At

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
2

There are 2 answers

3
janos On BEST ANSWER

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
0
repzero On

try using

You are doing a substitution so there is no need to sed -i '' and try using the shell default quotes "

if you are using sed in a script just enclose the variable $localip with double qoutes so that bash can do the substitution.

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