0

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!

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.