如何从 Markdown 文件中删除 YAML frontmatter? [英] How to remove YAML frontmatter from markdown files?

查看:36
本文介绍了如何从 Markdown 文件中删除 YAML frontmatter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包含 YAML frontmatter 元数据的 Markdown 文件,如下所示:

I have markdown files that contain YAML frontmatter metadata, like this:

---
title: Something Somethingelse
author: Somebody Sometheson 
---

但是 YAML 的宽度各不相同.当它位于文件的开头时,我可以使用像 sed 这样的 Posix 命令来删除它吗?只是删除 ------ 之间的所有内容,包括在内,但也会忽略文件的其余部分,以防有 ---s 其他地方.

But the YAML is of varying widths. Can I use a Posix command like sed to remove that frontmatter when it's at the beginning of a file? Something that just removes everything between --- and ---, inclusive, but also ignores the rest of the file, in case there are ---s elsewhere.

推荐答案

我理解你的问题的意思是你想删除第一个 ----enclosed 块,如果它从第一行开始.在这种情况下,

I understand your question to mean that you want to remove the first ----enclosed block if it starts at the first line. In that case,

sed '1 { /^---/ { :a N; /\n---/! ba; d} }' filename

这是:

1 {              # in the first line
  /^---/ {       # if it starts with ---
    :a           # jump label for looping
    N            # fetch the next line, append to pattern space
    /\n---/! ba; # if the result does not contain \n--- (that is, if the last
                 # fetched line does not begin with ---), go back to :a
    d            # then delete the whole thing.
  }
}
                 # otherwise drop off the end here and do the default (print
                 # the line)

根据您希望如何处理以 ---abc 开头的行,您可能需要稍微更改模式(也许在后面添加 $仅当整行为 --- 时才匹配).我有点不清楚您那里的确切要求.

Depending on how you want to handle lines that begin with ---abc or so, you may have to change the patterns a little (perhaps add $ at the end to only match when the whole line is ---). I'm a bit unclear on your precise requirements there.

这篇关于如何从 Markdown 文件中删除 YAML frontmatter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆