bash 使用 sed 在 txt 文件的第 1 行插入一个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22166470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert a variable at line #1 of txt file using sed
提问by MLSC
I have the following bash:
我有以下 bash:
#!/bin/bash
if ["$#" -ne "1"]; then
echo "Usage: `basename $IPADDR
` <HOSTNAME>"
exit 1
fi
IPADDR=`ifconfig | head -2 | tail -1 | cut -d: -f2 | rev | cut -c8-23 | rev`
sed -i -e '1i$IPADDR \' /etc/hosts
But when I cat /etc/hosts
:
但是当我cat /etc/hosts
:
sed -i -e '1i'$IPADDR' ''\' /etc/hosts
How can I deal with such issues?
我该如何处理此类问题?
回答by Benjamin Bannier
Your problem is that variables inside single quotes '
aren't expanded by the shell, but left unchanged. To quote variables you want expanded use double quotes "
or just leave off the quotes if they are unneeded like here, e.g.
您的问题是单引号内的变量'
没有被 shell 扩展,而是保持不变。要引用您想要扩展的变量,请使用双引号,"
或者如果不需要像这里这样的引号,则省略引号,例如
#!/bin/bash
IPADDR=$(/sbin/ifconfig | head -2 | tail -1 | cut -d: -f2 | rev | cut -c8-23 | rev)
sed -i -e "1i${IPADDR} " /etc/hosts
In above line $IPADDR
and $1
are outside of quotes and will be expanded by the shell before the arguments are being feed to sed
.
在上面的行中$IPADDR
,$1
并且在引号之外,并且在将参数提供给sed
.
回答by chooban
The single quotes mean the string isn't interpolated as a variable.
单引号表示该字符串未作为变量进行插值。
##代码##I also did the command in $(...)
out of habit!
我也$(...)
习惯性地做了命令!