简体   繁体   中英

Using a regex from a variable in awk

I have a file with records separated by empty lines, something like this:

ID0
field1
field2
field3

ID1
field1
field2
field3

ID2
field1
field2
field3

...

So, to get all content of a record based on its ID I use awk 'BEGIN {RS=""} /ID1/' file

But, the issue is that I would like to make it with a script, with the id passed as a variable.

I have written the script like that (but it doesn't work):

#! /usr/bin/awk -f

# Set Record Separator
BEGIN {RS=""}

# Search that record that contains the id
/id/

I call it with ./script.awk -v id=ID1 file

Any help?

Thanks!

It's not caused by being in a script (as the original question title asserted): You would see the same problem if you were running awk -v id=ID1 'BEGIN {RS=""} /id/' file . The way you're using /id/ isn't looking at the variable named id ; instead, it's expecting id to be the exact regex to match.

Instead of using /varname/ (which is treating varname as a regex itself instead of the name of a variable containing a regex), use $0 ~ varname :

#! /usr/bin/awk -f

# Set Record Separator
BEGIN {RS=""}

# Search that record that contains the id
$0 ~ id

See this demonstrated in the online interpreter at https://ideone.com/amz1u1

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