将 shell 参数传递给 awk 正则表达式

Pass shell parameters to awk regex

我有以下脚本

#!/bin/bash
file="path/to/file"
/usr/bin/awk '/chapter:/ {f=0} /chapter: 25/ {f=1} f' $file

如何使用变量的值而不是 25

像这样:

#!/bin/bash
file="path/to/file"
num=25
/usr/bin/awk '/chapter:/ {f=0} /chapter: <num>/ {f=1} f' $file

p.s。

  1. /usr/bin/awk -v n="$num" '/chapter:/ {f=0} /chapter: n/ {f=1} f' $file不工作
  2. 我不能为此使用任何其他工具,因为 awk 是我想要做的最快的工具

有什么想法吗?

除了构建正则表达式的第二部分,您的方向是正确的。您可以使用:

awk -v n="$num" '/chapter:/{f=0} [=10=] ~ "chapter: " n {f=1} f' file

您需要使用变量 n 构建正则表达式并使用 ~ 运算符进行正则表达式匹配。