1

我是一个 n00b,试图将我的 IP 地址返回给一个变量,然后在 bash 脚本中的 sed 命令中使用该变量。我正在尝试用我的 IP 地址替换文件中的文本“mycomputer”,但运气不佳。

这是我的尝试:

1

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

我收到的错误是:

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

2

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

将 'mycomputer' 更改为 '$localip' - 不是实际的 IP 地址

3

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

错误:

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

有什么想法吗?!?!

编辑

这用于 bash 脚本,如下所示:

#!/bin/bash

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

2 回答 2

2

你弄错了双引号:

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

这应该有效(注意区别):

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

实际上,您在其他线路上也有类似的问题。所以完整的脚本,更正:

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

请注意,这-i ''是针对 BSD 版本的sed(在 BSD 系统和 MAC 中)。在 Linux 中,你可以这样写:

sed -i "s/mycomputer/$localip/" config.txt
于 2014-12-15T21:55:36.573 回答
0

尝试使用

您正在进行替换,因此无需sed -i ''尝试使用 shell 默认引号"

如果您在脚本中使用 sed,只需将变量$localip用双引号括起来,以便 bash 可以进行替换。

sed -i s/mycomputer/"$localip"/ config.txt
于 2014-12-15T22:15:37.113 回答