sed:使用另一个文件的内容修改一个文件
我有一个将 IP 地址写入文件 ip.txt
的脚本,
我想用 ip.txt
中的 IP 替换 html 文件中的 IP 地址。
我有一个与 IP 地址匹配的 sed 正则表达式,我想用 ip.txt
的内容替换这个匹配的文本:
"s/\([0-9] \{1,3\}\.\)\{3\}[0-9]\{1,3\}//g"
我怎样才能让 sed
拉取ip.txt
的内容并放入它在表达式 s/
中吗?
还有比这更好的方法吗?
sed -e "s/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/"`cat ip.txt`"/g"
I've got a script which writes an ip address to a file ip.txt
I want to replace an ip address in an html file with the ip from ip.txt
.
I've got a sed regex expression that matches an ip address, and I want to replace this matched text with the contents of ip.txt
:
"s/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}//g"
How can I get sed
to pull the contents of ip.txt
and put it in the expression s/<search>/<*HERE*>/g
?
Is there a better way to do it than this?
sed -e "s/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/"`cat ip.txt`"/g"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有太大的改进,但您可以替换
为
which 将替换为文件的内容,并且比使用
cat
效率稍高。Not much of an improvement, but you can replace
with
which will be replaced with the contents of the file and is slightly more efficient than using
cat
.您可以在运行 sed 命令之前将 IP 读入 shell 变量。假设 ip.txt 是仅包含 IP 地址的单行:
You can read the IP into a shell variable before running the sed command. Assuming that ip.txt is a single line containing only the IP address:
POSIX
sed
(以及大多数sed
的可用实现)支持r file
命令在匹配行时读取文件。只要您不介意结果在 IP 地址两侧包含换行符,您就可以使用r
轻松完成此操作。描述说:这意味着您没有机会编辑文件的内容,而如果将其读入模式空间或保留空间,则可以修改数据。
在这种情况下,您的命令行替换就已经是您能做的最好的了。
POSIX
sed
(and therefore most of the available implementations ofsed
) supports ther file
command to read a file when a line is matched. As long as you don't mind have the result containing newlines either side of where the IP address was, you could easily enough do it usingr
. The description says:This means that you don't get a chance to edit the contents of the file, whereas if it was read into the pattern space or hold space, you could could then modify the data.
This being the case, your command line substitution is about as good as you can do.