guillem
guillem

Reputation: 3

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!

Upvotes: 0

Views: 73

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 296049

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

Upvotes: 1

Related Questions