sed:使用另一个文件的内容修改一个文件

发布于 2024-12-20 14:29:06 字数 472 浏览 0 评论 0原文

我有一个将 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//<*HERE*>/g 中吗?

还有比这更好的方法吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

红ご颜醉 2024-12-27 14:29:06

没有太大的改进,但您可以替换

"`cat ip.txt`"

$(<ip_txt)

which 将替换为文件的内容,并且比使用 cat 效率稍高。

Not much of an improvement, but you can replace

"`cat ip.txt`"

with

$(<ip_txt)

which will be replaced with the contents of the file and is slightly more efficient than using cat.

月寒剑心 2024-12-27 14:29:06

您可以在运行 sed 命令之前将 IP 读入 shell 变量。假设 ip.txt 是仅包含 IP 地址的单行:

read -r ip < ip.txt
sed -e "s/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/$ip/g" file.html > newfile.html
mv newfile.html file.html

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:

read -r ip < ip.txt
sed -e "s/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/$ip/g" file.html > newfile.html
mv newfile.html file.html
冰雪梦之恋 2024-12-27 14:29:06

POSIX sed(以及大多数 sed 的可用实现)支持 r file 命令在匹配行时读取文件。只要您不介意结果在 IP 地址两侧包含换行符,您就可以使用 r 轻松完成此操作。描述说:

[1addr]r rfile

rfile的内容复制到标准输出,如前所述。如果rfile不存在或无法读取,则应将其视为空文件,不会导致错误情况。

这意味着您没有机会编辑文件的内容,而如果将其读入模式空间或保留空间,则可以修改数据。

在这种情况下,您的命令行替换就已经是您能做的最好的了。

POSIX sed (and therefore most of the available implementations of sed) supports the r 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 using r. The description says:

[1addr]r rfile

Copy the contents of rfile to standard output as described previously. If rfile does not exist or cannot be read, it shall be treated as if it were an empty file, causing no error condition.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文