【问题标题】:How to use sed comand to replace HTML text with text from another file?如何使用 sed 命令将 HTML 文本替换为另一个文件中的文本?
【发布时间】:2022-01-26 16:06:34
【问题描述】:

我有 2 个 html 文件。

  • index.html 在名为“main”的文件夹中
  • other.html 位于名为“other”的文件夹中

index.html 代码如下:

<h1>My first story</h1>
<p>The pen was blue.</p>

other.html 有以下代码:

<p>The pen was black.</p>

我想用 other.html 的全部内容替换“index.html”中的段落内容,以便 index.html 给出以下结果:

<h1>My first story</h1>
<p>The pen was red.</p>

我尝试使用终端命令cd main &amp;&amp; sed -e "s_&lt;p&gt;The pen was blue.&lt;/p&gt;_$(cd ../other &amp;&amp; sed 's:/:\\/:g' other.html)_" index.html,但收到错误消息“bash: cd: main: No such file or directory”。即使我尝试将它们放在同一个目录中以进行测试,它也不起作用。但我需要将它们放在单独的文件夹中。

更新:我通过使用命令 sed -e "s_&lt;p&gt;The pen was blue.&lt;/p&gt;_$(sed 's:/:\\/:g' other/other.html)_" main/index.html 修复了访问不同目录中文件的问题,但现在我收到错误消息 "sed: -e expression #1, char 54: unterminated `s' command"

如何让它将第二个文件的内容复制到第一个文件中?

【问题讨论】:

  • 如果 cd main 则没有其他方法可以工作,因此请先调试,然后在需要帮助时询问其余部分。
  • @EdMorton 我调试了“cd main”部分,但它仍然显示错误,因为它无法识别第二个文件的内容。
  • 它是否必须被sed?为什么不使用python? | @edit python -c 'stuff'perl -pe 'stuff' 也是一个“命令行”。基本上每个命令都是命令行 - echo "int main() { }" | gcc -xc - &amp;&amp; ./a.out
  • @KamilCuk 我想为此使用命令行。
  • stackoverflow.com/questions/407523/… 会回答您的问题吗?首先将文件读入字符串 - 然后转义。因为换行符链接到stackoverflow.com/questions/29613304/…

标签: sed replace command-line


【解决方案1】:

通过使用Is it possible to escape regex metacharacters reliably with sed带有多行替换字符串的部分,尝试以下操作:

IFS= read -d '' -r < <(sed -e ':a' -e '$!{N;ba' -e '}' -e 's/[&/\]/\\&/g; s/\n/\\&/g' other.html)
replaceEscaped=${REPLY%$'\n'}

sed -e "s_<p>The pen was blue.</p>_$replaceEscaped_" main/index.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 2014-12-28
    • 2018-01-11
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 2017-08-23
    相关资源
    最近更新 更多