简体   繁体   English

将命令结果传递给SED

[英]passing the result of a command to SED

I want do to the following, get the host ip of my server and then use this value to substitute a dummy value in a config file. 我要执行以下操作,获取服务器的主机ip,然后使用此值替换配置文件中的虚拟值。

For step 1 to get the server ip I call: 对于获取服务器IP的步骤1,我致电:

hostname -I | head -n1 | awk '{print $1;}'

For step 2 to replace the dummy value in the file I would do: 对于步骤2替换文件中的虚拟值,我将执行以下操作:

sed -i 's/dummyvalue/valuefromprevioushostnamecommand/g' filename.

The idea is to combine this steps into one unix command without using any shell scripting. 这个想法是将这些步骤组合成一个unix命令,而不使用任何shell脚本。

Any help on this would be greatly appreciated Rob 任何对此的帮助将不胜感激Rob

You are almost there - just nest the two commands within each other: 您快到了,只需将两个命令相互嵌套即可:

sed -i s/'dummyvalue'/$(hostname -I | head -n1 | awk '{print $1;}')/g filename

Note that you need to remove the surrounding single-quotes around the s///g , and placed them around the dummyvalue instead. 请注意,您需要删除s///g周围的单引号,并将其放在dummyvalue周围。 Otherwise bash won't try to interpret the inner command. 否则,bash不会尝试解释内部命令。

You do not need a chain of piped commands when you are using awk. 使用awk时,不需要一连串的管道命令。 Just do it in one awk command. 只需执行一个awk命令即可。 You didn't show any sample input and expected output so this is obviously untested but will be close to what you need if not exactly: 您没有显示任何样本输入和预期输出,因此显然未经测试,但如果不完全接近,它将接近您的需求:

hostname -I |
awk -i inplace 'NR==FNR{if (FNR==1) val=$1; nextfile} {gsub(/dummyvalue/,val)} 1' - filename

The above uses gawk 4.* for -i inplace and nextfile , with other awks just do: 上面的代码对-i inplace nextfilenextfile使用gawk 4. *,而其他awks只是这样做:

hostname -I |
awk 'NR==FNR{if (FNR==1) val=$1; next} {gsub(/dummyvalue/,val)} 1' - filename > tmp && mv tmp filename

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

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