You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Pelican迁移至Hugo:解析迁移Markdown文件的Awk脚本

Understanding the c Variable in This Pelican-to-Hugo Awk Script

Great question—let’s clear up the confusion: c and !c are not custom functions—they’re simple variable checks that act as a state flag to control how the script processes each line of your Markdown file. Here’s a step-by-step breakdown:

First: Awk’s Variable Basics

In Awk, uninitialized variables default to an empty string (which evaluates to false in boolean contexts). c is just a plain flag variable we use to track whether we’ve finished processing the YAML frontmatter.

What does c=1 mean?

c=1 is an assignment: it sets the variable c to the value 1. In Awk, any non-zero number (or non-empty string) is treated as true in boolean checks. So this line flips our flag from "not done with frontmatter" to "done with frontmatter".

Line-by-Line Breakdown of the Script

Let’s walk through each block to see how c works:

1. BEGIN Block (Runs once at start)

BEGIN { FS = ":"; OFS = ":"; print "---" }
  • Sets field separator (FS) and output field separator (OFS) to :
  • Prints the opening --- for Hugo’s YAML frontmatter

2. The Flag Trigger

!c && /^$/ { print "---\n"; c = 1 }
  • !c: Checks if c is false (we haven’t finished frontmatter yet)
  • /^$/: Checks if the current line is empty (this marks the end of Pelican’s frontmatter)
  • When both conditions are true:
    • Print --- to close Hugo’s frontmatter
    • Set c=1 to flip the flag—now we’ll treat all subsequent lines as post content

3. Process Post Content

c { print; next }
  • c: Checks if c is true (we’re past the frontmatter)
  • If true: Print the line as-is, then use next to skip the rest of the script logic for this line (no need to modify post content)

4. Process Frontmatter Lines

!c {
    # lower first field
    $1 = tolower($1)
    # if first field is "date"
    if ($1 == "date") {
        # transform second field
        $2 = gensub(/ ([^.]+)\.([^.]+).([^.]+)/, " \\3-\\2-\\1", 1, $2)
        $2 = gensub(/-([0-9])-/, "-0\\1-", 1, $2)
    }
    if ($1 == "tags")
        $2 = " [" gensub(/[-a-z]+/, "'\\0'", "g", substr($2, 2)) "]"
    print
}
  • !c: Checks if c is false (we’re still processing frontmatter)
  • For each frontmatter line:
    • Convert the key (first field) to lowercase (Hugo prefers lowercase frontmatter keys)
    • Rewrite the date field to match Hugo’s YYYY-MM-DD format
    • Rewrite the tags field to use Hugo’s array syntax (e.g., ['tag1', 'tag2'])
    • Print the modified line

Key Takeaway

c is just a state switch:

  • !c = "we’re still in the frontmatter, modify this line"
  • c = "we’re in the post content, leave this line alone"
  • c=1 = "flip the switch—we’re done with frontmatter now"

内容的提问来源于stack exchange,提问作者Nsukami _

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:05:52