繁体   English   中英

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

[英]Replace file line with multi-line, special char string

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

这个想法是:

  1. 生成 markdown 表字符串,如...

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

    *简化

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

  2. readme_template.md文件中的<!-- insert-table-here -->替换为完整表

    ## Header <.-- insert-table-here --> <sub>More info...</sub>
  3. 将新文件另存为README.md

我无法让第 2 步工作。

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

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

我已经找到了一些针对具有特定字符的特定情况的破解解决方案,但我想确定一种更强大的方法。

编辑:感谢@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
{}-()[]/<>
!

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM