sed - Replace string with file contents

Hello,

I have two files: file1 and file2

file1 has the following info:

---
  host: "localhost"
  port: 3000
  reporter_type: "zookeeper"
  zk_hosts: 
    - "localhost:2181"

file2 contains an IP address (1.1.1.1)

What I want to do is replace localhost with 1.1.1.1, so that the end result is:

---
  host: "1.1.1.1"
  port: 3000
  reporter_type: "zookeeper"
  zk_hosts: 
    - "1.1.1.1:2181"

I have tried:

sed -i -e "/localhost/r file2" -e "/localhost/d" file1
sed '/localhost/r file2' file1 |sed '/localhost/d'
sed -e '/localhost/r file2' -e "s///" file1

but I either get the whole line replaced, or the ip going to the line after the one I need to modify.

Have spent around 4 hours searching various forums, with no luck whatsoever.

Please advise.

Thank you!

If the file2 contains only IP address

awk 'NR==FNR {ip=$0;next} {gsub("localhost",ip)}1 ' file2 file1

Another way

read ip < file2
sed "s/localhost/$ip/" file1

Btw, you need to be a better googler :stuck_out_tongue:

And what is "ip" in this case? The name of the file?

Don't get it

And btw it will always be different on every execution, so adding it as a variable won't work. I am specifically looking for a SED (or awk) method

As you said, your file2 contains the ip address. file1 is the text where you have the localhost string. file1 and file2 in my solution are the filenames.

Oh, the second one works great, thanks a lot!