如何在 macOS 上使用 gsed 将字符串替换为文件内容?

How do I use gsed on macOS to replace a string with the contents of a file?

我需要一个文本文件,具体来说是一个 index.html,并将另一个文本文件的内容插入到该文本文件的特定位置,但不是在行尾。

我明白了如何用字符串替换(替代)文本,如下:

gsed 's/WHAT_TO_SUBSTITUTE/WHAT_TO_SUBSTITUTE_WITH/' index.html > index-new.html

然而,当我尝试用文件的内容替换时,我 运行 遇到了问题。这是我尝试过的:

gsed 's/<!--New Posts Go Below This Line-->/r newpost.txt/' index.html > index-new.html

以上根本行不通

gsed -s '/<!--New Posts Go Below This Line-->/ r newentry.txt' index.html > index-new.html

上面插入了文件的内容,但是在行尾而不是替换字符串(如预期的那样)

文本文件的内容:

<!--New Posts Go Below This Line--> <div class=panel panel-default><div class=panel-heading><h4 class=panel-title><a data-parent=#accordion data-toggle=collapse href=#collapse56> February 31st, 2069 - New Post </a></h4></div><div class=panel-collapse collapse  id=collapse56><div class=panel-body><img alt=my_favorite_image.png div= src=/render/file.act?path=/my_favorite_image.png /></div></div></div>

预期输出(请记住,由于我公司的 CMS,我正在使用的 html 一旦写入网络服务器就会成为一个大块):

....index.html_HTML_code....<!--New Posts Go Below This Line-->CONTENTS_OF_newpost.txt.....index.html_HTML_code....

要用 newpost.html 中的内容替换 <!--New Posts Go Below This Line-->,您可以坚持使用简单的 shell 命令替换:

gsed "s/<!--New Posts Go Below This Line-->/$(cat newpost.txt)/" index.html > index-new.html

编辑:

这仅在 newpost.txt 不包含换行符时有效。用 sed 做多行的事情非常困难,因为语法非常晦涩难读。

我强烈推荐另一个工具来完成这项工作。例如 Perl:

perl -pe 's/<!--New Posts Go Below This Line-->/`cat newpost.txt`/ge' index.html > index-new.html

假设匹配项单独占一行,您可以插入文件并删除模式-space,例如:

parse.sed

/<!--New Posts Go Below This Line-->/ {
  r newentry.txt
  d
}

运行 像这样:

sed -f parse.sed

或作为单行:

sed $'/<!--New Posts Go Below This Line-->/ { r newentry.txt\n d; }'

编辑

如果匹配是该行的子串,使用s///代替d,例如:

parse.sed

/<!--New Posts Go Below This Line-->/ {
  r newentry.txt
  s///
}