Insert external variable in a AWK pattern

Dear all,

�How can i insert a variable in a AWK pattern?

I have almost succeeded in solving a puzzle with AWK but now i want to make a script. Let me explain.

cat file.txt | awk 'BEGIN {RS="\\n\\n"} /tux/  { print "\n"$0 }'

I know that this command makes right what i want to do, but mi intention is make a generic script whit a input parameter instead of 'tux' constant. Can you help me please?

Thanks

Something like this ?

awk -v var_name="value"  '##use the variable as you wish' input_filename.txt

No way, if i put this in the command does not works, it only takes the variable in the print field.

Doesn't works:

cat file.txt  | awk -v var_name=$id 'BEGIN {RS="\\n\\n"} /var_name/  { print "\n"$0 }'

Works, but i dont want use the variable there

cat file.txt  | awk -v var_name=$id 'BEGIN {RS="\\n\\n"} /tux/  { print var_name "\n"$0 }'

You need:

$0 ~ var_name

not:

/var_name/

And in this case you don't need to call external commands like cat.

Still not working...

cat file.txt | awk 'BEGIN {RS="\\n\\n"} $0 ~ '$id'  { print "\n"$0 }'

cat file.txt | awk 'BEGIN {RS="\\n\\n"} $0 ~ $id  { print "\n"$0 }'

cat file.txt | awk -v var_name=$id 'BEGIN {RS="\\n\\n"} $0 ~ var_name  { print "\n"$0 }'

I said:

$0 ~ var_name

not:

$0 ~ $var_name

And you need to set the variable for AWK as the previous poster pointed out:

% print -l a b | awk -vvar=a '$0 ~ var'
a
% print -l a b | awk '$0 ~ var' var=a
a

...

In your case it would be:

awk -vid=$id 'awk 'BEGIN {RS="\\n\\n"}  $0 ~ id  { print "\n" $0 }' file.txt

Or probably just:

awk '$0 ~ id' RS= id=$id file.txt 

i tested all cases.
note that $id is an external variable, and its what i want to put as AWK pattern.. Should I use the -v option ? Please complete my command, so I will understand you better. thanks

See my further comments in the previous post.

---------- Post updated at 11:37 AM ---------- Previous update was at 11:32 AM ----------

It seems you're using GNU AWK (you're using multi-character RS).
So, if the external variable is exported you can use something like this:

$0 ~ ENVIRON["id"]

In this last case you don't need to use pre (-v) or post (var= ...) assignment.

Thank you for your help radoulov,

In the end I got the brute force solution, redirecting the command to an aux script file pasting the external variable into the awk command and executing the file. It is not the most elegant solution, but it's working properly.:slight_smile: