用多行、特殊字符串替换文件行

Replace file line with multi-line, special char string

我正在尝试自动生成 README.md

想法是:

  1. 生成 markdown table 字符串...

    table="| Image | Name | Description | Notes |\n"
    table+="| --- | --- | --- | --- |\n"
    table+="| $img1 | $name1 | $desc1 | $notes1 |\n"
    table+="| $img2 | $name2 | $desc2 | $notes2 |\n"
    ...
    

    *简化

    *包含特殊字符,例如|-()[]/<>

  2. 用完整的 table

    替换 readme_template.md 文件中的 <!-- insert-table-here -->
    ## Header
    
    <!-- insert-table-here -->
    
    <sub>More info...</sub>
    
  3. 将新文件另存为README.md

我无法执行第 2 步。

如何用多行、特殊的字符字符串替换文件中的一行?

我尝试的每个 sedawkperl 甚至 head/tail 命令似乎都不起作用。 heredocs 是更好的方法吗?

我找到了一些针对特定字符的特定情况的 hack 解决方案,但我想确定一种更可靠的方法。

编辑:感谢@potong,这就是最终为我工作的东西。

echo -e ${table} | sed -e '/<!-- insert-table-here -->/{r /dev/stdin' -e 'd}' readme_template.md > README.md

编辑 2:在这上面花了更多时间后,我通过 awk

找到了一个不错的多重匹配选项
awk \
  -v t1="$(generate_table1)" \
  -v t2="$(generate_table2)" \
  '{
    gsub(/<!-- insert-table-1 -->/,t1)
    gsub(/<!-- insert-table-2 -->/,t2)
  }1' \
  readme_template.md > README.md

这可能对你有用(GNU sed 和 bash):

cat <<\! | sed -e '/<!-- insert-table-here -->/{r /dev/stdin' -e 'd}' file
Here is a heredoc
with special symbols
{}-()[]/<>
!

heredoc 使用 /dev/stdin 作为 r 命令的文件通过管道传递给 sed 命令,然后使用 d 命令删除原始行。

N.B。使用 -e 命令行选项来拆分 sed 脚本(oneliner)的两部分。这是必要的,因为 r 命令需要用换行符终止,而 -e 选项提供了此功能。