Jay*_*Kah 33 sed text-processing
我有两个文件:file1和file2.
file1 有以下内容:
---
host: "localhost"
port: 3000
reporter_type: "zookeeper"
zk_hosts:
- "localhost:2181"
Run Code Online (Sandbox Code Playgroud)
file2包含一个 IP 地址 ( 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"
Run Code Online (Sandbox Code Playgroud)
我试过了:
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
Run Code Online (Sandbox Code Playgroud)
但是我要么替换整条线路,要么将 IP 放到我需要修改的线路之后。
cuo*_*glm 21
这是一个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"
Run Code Online (Sandbox Code Playgroud)
您应该使用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"
Run Code Online (Sandbox Code Playgroud)
Vol*_*gel 13
在使用之前,您可以使用 shell 命令替换读取带有替换字符串的文件sed。所以sed只会看到一个正常的替换:
sed "s/localhost/$(cat file2)/" file1 > changed.txt