sed - 文字列をファイルの内容に置き換える

sed - 文字列をファイルの内容に置き換える

2つのファイルがあります:file1file2

file1以下の内容があります。

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

file2IPアドレスを含む(1.1.1.1

私がやりたいことは、最終結果が次localhostのように変わることです。1.1.1.1

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

私は試した:

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

ただし、ライン全体を交換または変更する必要があるラインの次の行にIPを移動する必要があります。

ベストアンサー1

解決策は次のとおりですsed

% sed -e "s/localhost/$(sed 's:/:\\/:g' file2)/" file1
---
  host: "1.1.1.1"
  port: 3000
  reporter_type: "zookeeper"
  zk_hosts: 
    - "1.1.1.1:2181"

sed -iこれを適切に変更するには、それを使用する必要があります。

利用可能な場合は、awk次の方法があります。

% awk 'BEGIN{getline l < "file2"}/localhost/{gsub("localhost",l)}1' file1
---
  host: "1.1.1.1"
  port: 3000
  reporter_type: "zookeeper"
  zk_hosts: 
    - "1.1.1.1:2181"

おすすめ記事