bob dabelina
bob dabelina

Reputation: 537

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

Upvotes: 0

Views: 610

Answers (2)

Ed Morton
Ed Morton

Reputation: 204731

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

Upvotes: 1

Martin Konecny
Martin Konecny

Reputation: 59701

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.

Upvotes: 3

Related Questions