如何用cat&grep从YAML提取post_content并按post_name分存至.html文件?
我来帮你搞定这个需求!要实现把每个条目里的post_content提取出来,并存到以对应post_name命名的.html文件里,这里给你两种实用方案,按需选择:
方案1:用yq(推荐,处理YAML更可靠)
yq是专门用来处理YAML/JSON的命令行工具,语法简洁还不容易出错,先确保你已经安装了它(比如用brew install yq或者sudo apt install yq就能搞定)。
如果你的posts.yaml是单个条目或者多个用---分隔的独立文档,直接运行这条命令:
yq e '(.post_name + ".html") as $filename | .post_content | trim | writefile($filename)' posts.yaml
要是你的YAML是数组格式(比如每个条目都是- post_content: ...这种数组元素),就加个.[]来遍历数组:
yq e '.[] | (.post_name + ".html") as $filename | .post_content | trim | writefile($filename)' posts.yaml
简单解释下命令逻辑:
(.post_name + ".html") as $filename:把当前条目的post_name拼接上.html后缀,存成文件名变量.post_content | trim:提取post_content的内容,同时去掉文本前后多余的空格(比如你示例里开头的空格)writefile($filename):把处理后的内容写入对应的HTML文件
方案2:用awk(无需额外安装工具)
如果不想装新工具,用系统自带的awk也能实现,先把下面的代码保存成extract_posts.awk脚本:
BEGIN { RS = "---" # 用---分隔每个YAML条目 FS = "\n" # 每行作为一个单独字段 } { content = "" name = "" # 遍历当前条目里的每一行 for (i=1; i<=NF; i++) { # 提取post_content内容,去掉键名、前后引号和空格 if ($i ~ /^post_content: /) { content = substr($i, 15) gsub(/^[" ]+|[" ]+$/, "", content) } # 提取post_name作为文件名 if ($i ~ /^post_name: /) { name = substr($i, 12) gsub(/^[" ]+|[" ]+$/, "", name) } } # 只有同时拿到内容和文件名时,才写入文件 if (name != "" && content != "") { print content > (name ".html") close(name ".html") # 关闭文件,避免打开过多句柄 } }
然后运行脚本处理你的YAML文件:
awk -f extract_posts.awk posts.yaml
两种方案都能帮你把示例里的post_content内容存入kontakt.html文件里,完全符合你的需求~
内容的提问来源于stack exchange,提问作者TheRojam
相关产品推荐
相关产品推荐

