简体   繁体   中英

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.

For step 1 to get the server ip I call:

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

For step 2 to replace the dummy value in the file I would do:

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

The idea is to combine this steps into one unix command without using any shell scripting.

Any help on this would be greatly appreciated 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. Otherwise bash won't try to interpret the inner command.

You do not need a chain of piped commands when you are using awk. Just do it in one awk command. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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