繁体   English   中英

变量在sed内的shell脚本中不起作用

[英]variable not working in shell script inside sed

我有变量jr=127.0.1.1 ysrnsk 我必须将它替换为我的/etc/hosts文件的第二行。 sudo sed -i.bak '2 s/^.*$/'$jr'/' /etc/hosts这就是我所做的。 但它不提供任何输出

由于您使用的是-i选项,因此sed命令不会输出任何内容

你必须双重引用一切:

jr="127.0.1.1 ysrnsk"
sudo sed -i.bak "2 s/^.*$/$jr/" /etc/hosts
jr="127.0.1.1 ysrnsk"

^^在此处提供报价,表示包含所有数据,否则您的输入仅为127.0.1.1

sed -i.bak '2 s/^.*$/$jr/' /etc/hosts

-i参数使编辑到位。 哪个不提供输出。 如果要在编辑之前“测试”输出,请运行

sed .bak "2 s/^.*$/'$jr'/" /etc/hosts

''在bash中字面意思是你键入的内容。要允许参数扩展,例如将变量转换为实际含义,请使用双引号""

sed .bak "2 s/^.*$/'$jr'/" /etc/hosts
                   ^   ^ These don't do anything, other than again, tell bash to interpret this literally

所以:

sed .bak "2 s/^.*$/$jr/" /etc/hosts # This to see your output
sed -i .bak "2 s/^.*$/$jr/" /etc/hosts # This to commit it without output

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM