awk-posix-compat

Solid

Shell 脚本中 awk 的 POSIX 兼容性指南。 Use when: 编写或审查包含 awk 的 shell 脚本, 尤其是需要 macOS + Linux 跨平台运行的场景。 触发词: awk, BSD awk, POSIX regex, [[:space:]], guard 脚本, 跨平台 shell

AI & Automation 36 stars 6 forks Updated today MIT

Install

View on GitHub

Quality Score: 83/100

Stars 20%
52
Recency 20%
100
Frontmatter 20%
70
Documentation 15%
100
Issue Health 10%
50
License 10%
100
Description 5%
100

Skill Content

# awk POSIX 兼容性指南 ## Problem macOS 自带 BSD awk 严格遵循 POSIX 标准,不支持 GNU awk (gawk) 的正则扩展。 在 Linux (gawk) 开发、macOS (BSD awk) 运行时**静默匹配失败** — 无报错但结果为空。 这类 bug 极难调试:脚本不报错,只是检测不到任何匹配,看起来像"没有问题"。 ## When to Activate - 编写包含 `awk '...'` 的 shell 脚本 - 脚本需要在 macOS + Linux 上运行 - 使用 awk 正则做代码模式检测(guard/linter/hook) - 错误现象:Linux 上能检测到问题,macOS 上检测为 0 ## When to Activate - A shell guard or hook uses `awk` regexes and must run on both macOS and Linux. - A pattern works under GNU awk but silently misses under BSD awk. - A guard needs brace-depth, loop-scope, or nested-function analysis in plain POSIX awk. ## Solution ### 1. 正则替换规则(6 条) | GNU awk 扩展 | POSIX 替代 | 说明 | |-------------|------------|------| | `\s` | `[[:space:]]` | 空白字符 | | `\S` | `[^[:space:]]` | 非空白字符 | | `\d` | `[0-9]` | 数字 | | `\w` | `[A-Za-z0-9_]` | 单词字符 | | `\b` | `[[:<:]]` / `[[:>:]]` | 词边界(BSD 语法) | | `\+` | `{1,}` 或重写模式 | 一次或多次 | ```bash # ❌ BAD — gawk 扩展,BSD awk 静默失败 awk '/\s+defer\s/' "$file" # ✅ GOOD — POSIX 兼容 awk '/[[:space:]]+defer[[:space:]]/' "$file" ``` ### 2. 字符级计数(gsub 法则) 禁止行级正则匹配计数大括号: ```bash # ❌ BAD — 单行多个 { 时只计 1 次 awk '/\{/ { depth++ }' "$file" # ✅ GOOD — gsub 返回替换次数 = 精确字符数 awk '{ tmp = $0; opens = gsub(/\{/, "", tmp) tmp = $0; closes = gsub(/\}/, "", tmp) depth += opens - closes }' "$file" ``` **原因**:`/{/` 是行级匹配 — 一行有 `func() { if x {` 两个 `{`,行级只计 1 次,导致 depth 跟踪错误,后续作用域判断全部偏移。 ### 3. 作用域隔离(嵌套结构检测) 检测"X 在 Y 内"的模式(如 `defer` 在 `for` 循环内)时,需要区分语法层级: ```bash # 需要 flit_depth 变量跟踪 func li...

Details

Author
majiayu000
Repository
majiayu000/vibeguard
Created
5 months ago
Last Updated
today
Language
Shell
License
MIT

Similar Skills

Semantically similar based on skill content — not just same category