简体   繁体   中英

Pass shell parameters to awk regex

I have the following script

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

how can I use a variable's value instead of 25 ?

something like this:

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

ps

  1. /usr/bin/awk -vn="$num" '/chapter:/ {f=0} /chapter: n/ {f=1} f' $file is not working
  2. I cannot use any other tool for that, because awk is the fastest one for what I want o do

any ideas?

You're on right track here but for the 2nd part of building the regex. You can use:

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

You need to build the regex using variable n and use ~ operator for regex matching.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM