从Pelican迁移至Hugo:解析迁移Markdown文件的Awk脚本
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 ifcisfalse(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=1to flip the flag—now we’ll treat all subsequent lines as post content
- Print
3. Process Post Content
c { print; next }
c: Checks ifcistrue(we’re past the frontmatter)- If true: Print the line as-is, then use
nextto 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 ifcisfalse(we’re still processing frontmatter)- For each frontmatter line:
- Convert the key (first field) to lowercase (Hugo prefers lowercase frontmatter keys)
- Rewrite the
datefield to match Hugo’sYYYY-MM-DDformat - Rewrite the
tagsfield 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 _

