如何从markdown文件中删除YAML frontmatter?

问题描述 投票:4回答:4

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

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

但是YAML的宽度各不相同。我可以使用像sed这样的Posix命令来删除文件开头的那个前端吗?什么东西只是删除------之间的所有内容,包括,但也忽略了文件的其余部分,以防其他地方有---s。

text-processing
4个回答
8
投票

我理解你的问题意味着你要删除第一个---封闭的块,如果它从第一行开始。在这种情况下,

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开头的行的方式,你可能需要稍微改变一下模式(也许最后添加$只匹配当整行是---时)。我对你的确切要求有点不清楚。


4
投票

如果你想删除前面的东西,只有前面的东西,你可以简单地运行:

sed '1{/^---$/!q;};1,/^---$/d' infile

如果第一行与---不匹配,sedquit;否则它将delete从1st系列到(并包括)匹配---的下一行(即整个前端事物)的所有内容。


1
投票

如果你不介意“或某事”是perl。

只需在找到两个“---”实例后打印:

perl -ne 'if ($i > 1) { print } else { /^---/ && $i++ }' yaml

如果你不介意滥用会有点短暂吗?:对于流量控制:

perl -ne '$i > 1 ? print : /^---/ && $i++' yaml

如果要替换内联,请务必包含-i


0
投票

你使用bash文件,创建script.sh并使用chmod +x script.sh使其可执行并运行它./script.sh

#!/bin/bash

#folder articles contains a lot of markdown files
files=./articles/*.md

for f in $files;
do
    #filename
    echo "${f##*/}"
    #replace frontmatter title attribute to "title"
    sed -i -r 's/^title: (.*)$/title: "\1"/' $f
    #...
done
© www.soinside.com 2019 - 2024. All rights reserved.