我正在尝试自动生成 README.md
.
想法是:
生成 Markdown 表字符串,例如...
table="| Image | Name | Description | Notes |\n" table+="| --- | --- | --- | --- |\n" table+="| $img1 | $name1 | $desc1 | $notes1 |\n" table+="| $img2 | $name2 | $desc2 | $notes2 |\n" ...
*简化
*包含特殊字符,例如
|-()[]/<>
替换
<!-- insert-table-here -->
在readme_template.md
包含完整表格的文件## Header <!-- insert-table-here --> <sub>More info...</sub>
将新文件另存为
README.md
我无法执行第 2 步。
如何用多行、特殊字符字符串替换文件中的一行?
每个sed
, awk
, perl
,甚至 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通过管道传输到 sed 命令,然后使用 删除原始行d
命令。
注意使用-e
命令行选项来分割sed脚本的两部分(oneliner)。这是必要的,因为 r
命令需要以换行符终止,而 -e
选项提供了此功能。
关于bash - 用多行特殊字符串替换文件行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67367239/