1

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
emeidos
  • 31
  • 4
  • 4
    Dn't use `“”’` quotes. they're not 'quotes' as far as the shell is concerned. e.g. don't use a wordprocessor as your code editor. – Marc B Dec 15 '14 at 21:54

2 Answers2

2

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
janos
  • 120,954
  • 29
  • 226
  • 236
  • thanks for this, not sure about the curly double quotes and where they came from. Your answer is still returning errors here. Maybe my shell script is the issue: #!/bin/bash cd "`dirname "$0"`" localip=`ipconfig getifaddr en0’ sed -i '' "s/mycomputer/$localip/" config.txt Error is: ./mytest.sh: line 4: unexpected EOF while looking for matching ``' ./mytest.sh: line 6: syntax error: unexpected end of file – emeidos Dec 15 '14 at 22:07
  • The formatting doesn't come out right in comments. Add that inside your question and I can have a look. Are you in Linux or what OS? – janos Dec 15 '14 at 22:10
  • aaagghh fixed it with your help! I re-edited with the wrong type of quote.. of course.. never knew about the standard vs curly single and double quotes.. thanks for your help! – emeidos Dec 15 '14 at 22:16
0

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
repzero
  • 8,254
  • 2
  • 18
  • 40