求批量在 md 文件里插入文本的方法

2019-03-04 13:21:16 +08:00
 dazkarieh

博客从 hexo 搬迁到 hugo,现 post 目录下有上千个 md 文件,因为主题设置的差异,要在 front-matter 部分插入一行 mathjax: false (严格来讲是 mathjax = false,不过 90%是 hexo 的源文件)。但有些 tag 设置是

tags :
 - AA
 - BB
 - CC

不想插到这部分标签之间。我的想法是,保守起见是否可以插到 title 一行后面。各位有经验的大佬给点建议!

3197 次点击
所在节点    编程
7 条回复
lynskylate
2019-03-04 13:35:43 +08:00
from pathlib import Path

dest_dir = Path(“你的目录")
md_files = dest_dir.glob("**/*.md")

def handle_file(filename):
rayhy
2019-03-04 13:35:57 +08:00
可以,不过有个问题,上千个 md 文件全部要加这个吗?为什么不直接改 hugo 的主题部分代码。。
lynskylate
2019-03-04 13:40:16 +08:00
```python
from pathlib import Path

dest_dir = Path("你的目录")
md_files = dest_dir.glob("**/*.md")

def handle_file(filename):
f = open(filename, "w")
lines = f.readlines()
dest_inx = 0
for inx, line in enumerate(lines):
if "title" in line: # 检测需要哪行包含检测的文字
dest_inx = inx
break
lines.insert(dest_inx, "mathjax = false")
f.write("".join(lines))
f.close()

for md in md_files:
handle_file(md)
```
没试 凭记忆写的
dazkarieh
2019-03-04 13:46:59 +08:00
@rayhy
不是特别懂 hugo 的代码,尝试过修改原主题的 mathjax 代码部分:

{{- if ne .Params.mathjax false }}
改成
{{- if eq .Params.mathjax true }}
,试了一下不起作用
————————————
{{- if ne .Params.mathjax false }}
<script src="/js/mathjax.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ['tex2jax.js'],
jax: ["input/TeX", "output/HTML-CSS"],
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
processEscapes: true,
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
},
TeX: {
extensions: ['AMSmath.js', 'AMSsymbols.js', 'noErrors.js', 'noUndefined.js', 'extpfeil.js']
},
"HTML-CSS": {
availableFonts: ["TeX"],
scale: 85
},
CommonHTML: {
scale: 85
},
SVG: {
scale: 85
}
});
</script>
<script async type="text/javascript" src="{{ $.Site.Params.CDN.MathJax.Path }}/mathjax/{{ $.Site.Params.CDN.MathJax.Version }}/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
{{- end }}
dazkarieh
2019-03-04 13:51:44 +08:00
@lynskylate 感谢!在外面,回去试试 @v@
4ark
2019-03-04 14:27:37 +08:00
ide 打开,搜索所有 md 共有的一段,然后替换(加上你想要新增的)
rayhy
2019-03-04 14:38:08 +08:00
@dazkarieh 你这样改,不成功的原因可能是,markdown 中.Params.mathjax 这个参数你本身的文件是没有设置的,直接调用是没反应的。所以{{- if nq .Params.mathjax true }}可以改成{{- if .Params.mathjax | default false -}}这样。参考 if 的文档: https://gohugo.io/templates/introduction/#example-3-if

不建议直接改 markdown 文件,改主题就行,多试几次。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/540813

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX