我有包含YAML frontmatter元数据的markdown文件,如下所示:
---
title: Something Somethingelse
author: Somebody Sometheson
---
但是YAML的宽度各不相同。我可以使用像sed
这样的Posix命令来删除文件开头的那个前端吗?什么东西只是删除---
和---
之间的所有内容,包括,但也忽略了文件的其余部分,以防其他地方有---
s。
我理解你的问题意味着你要删除第一个---
封闭的块,如果它从第一行开始。在这种情况下,
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
开头的行的方式,你可能需要稍微改变一下模式(也许最后添加$
只匹配当整行是---
时)。我对你的确切要求有点不清楚。
如果你想删除前面的东西,只有前面的东西,你可以简单地运行:
sed '1{/^---$/!q;};1,/^---$/d' infile
如果第一行与---
不匹配,sed
将q
uit;否则它将d
elete从1
st系列到(并包括)匹配---
的下一行(即整个前端事物)的所有内容。
如果你不介意“或某事”是perl。
只需在找到两个“---”实例后打印:
perl -ne 'if ($i > 1) { print } else { /^---/ && $i++ }' yaml
如果你不介意滥用会有点短暂吗?:对于流量控制:
perl -ne '$i > 1 ? print : /^---/ && $i++' yaml
如果要替换内联,请务必包含-i
。
你使用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