macOS下Awk脚本优化:忽略注释行及改进大小写匹配
优化后的Awk脚本方案
针对你提到的两个问题,这里给出适配macOS环境的优化脚本:
/^#/ { print; next } { tags = "" if (tolower($0) ~ /foo/) tags = tags "#foo " if (tolower($0) ~ /cat|dog/) tags = tags "#animal " if (tolower($0) ~ /text/) tags = tags "#text " print $0 tags }
关键改动说明
- 忽略以#开头的行:用
/^#/ { print; next }匹配行首为#的行,直接输出原内容并跳过后续标记处理,完全保留注释行的原始格式。 - 优化标记拼接逻辑:将标记拼接拆分为独立的条件判断,比原脚本的嵌套三元表达式更易读,也方便后续新增关键词规则;保留
tolower($0)处理,适配macOS的BSD Awk不支持IGNORECASE变量的特性,确保大小写不敏感匹配(比如Foo也能触发#foo标记)。
验证效果
假设输入文件内容为:
# cat.txt AB-1 text: foo AB-1 test3: test cat dog AB-1 test4: abc # cat2.txt AB-4 test: qwerty AB-5 test2: Foo bar AB-6 abc: Dog
执行脚本(将脚本保存为tag.awk,输入文件为input.txt):
awk -f tag.awk input.txt
输出结果与你期望的完全一致:
# cat.txt AB-1 text: foo#foo #text AB-1 test3: test cat dog#animal AB-1 test4: abc # cat2.txt AB-4 test: qwerty AB-5 test2: Foo bar#foo AB-6 abc: Dog#animal
内容的提问来源于stack exchange,提问作者KarlsD
相关产品推荐
相关产品推荐

