Let's say I run hostname -i and get the following output:

root@linux:/# hostname -i

How would I pipe that output (just the IP address) to replace a certain string in a given file?

I want to (i.e. using sed or awk) pipe the output of that command to the my_server_ip part below:

  • 1
    Could you share with us what have you tried so far? Sep 27, 2021 at 13:13
  • 1
    edit your question to clarify if you're trying to replace the literal string my_server_ip or trying to replace whatever string is within double quotes after "server" or something else.
    – Ed Morton
    Sep 27, 2021 at 13:16
  • Is the document that you want to change the text in a JSON document? If so, doing it with jq is more convenient and safer than with sed or awk. Could you possibly show more of the text file that you are working with?
    – Kusalananda
    Sep 27, 2021 at 17:02

4 Answers 4


I'm guessing you just want whatever is in quotes after "server" changed, not the specific string my_server_ip, and if so then using any sed:

$ sed 's/\("server":"\)[^"]*/\1'"$(hostname -i)"'/' file
"server":"<the host name>",

or any awk (more robust if the output of hostname -i could contain backreference metachars or sed delimiters, which it shouldn't):

$ awk -v h="$(hostname -i)" 'BEGIN{FS=OFS="\""} $2=="server"{$4=h} 1' file
"server":"<the host name>",

You can use substitution parameter like : sed -i -e "s/my_server_ip/$(hostname -i)/" txt


If you're using GNU sed, then you can use the /e flag to the s/ command, but the command executed is the whole line:

#!/bin/sed -f
s/.*/printf '&' $(hostname -i)/e

This creates a command line that looks like printf '"server":"%s",' $(hostname -i) and then executes it, replacing the relevant line.

m=$(hostname -i)
sed -i "s/my_server_ip/$m/g" filename

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .