Variable in awk command

Hello All,

I am trying to run a script to extract data from the file. The format of the file is as below:
filename: sample.log

12345| ABCD
23456| GKHY
33454| ABCD
98765| TTRR

I want to run a command in AWK as show below

extract.sh

#!/bin/bash

echo '***************************************************'
echo ' '
file_name='sample.log'

reqd_str=$1

str_list=${reqd_str}'_extracted_on_'$(date  +'%Y%m%d-%H%M%S').'log'

#Below doesn't work#

awk 'BEGIN { FS ="|" }{ if ( $2 ~ /$reqd_str/ ) print $1 > $str_list}'  file_name

# Below AWK command does work #
#awk 'BEGIN { FS ="|" }{ if ( $2 ~ /ABCD/ ) print $1 > "output.txt"}'  sample.log

i will be executing file in below way

/> ./extract.sh ABCD

So the above executing should bring me back below result in an output file

12345
33454

I am happy to replace AWK with some other command as long as it serve the purpose. Basically i was script to extract ABCD i.e. field 2 and extract field 1.

The single quotes prevent the shell variables from being expanded. A better method is to use awk variables and pass shell variables to them using the -v option:

Try something like this:

awk -v regd_str="$reqd_str" -v str_list="$str_list" 'BEGIN { FS ="|" }{ if ( $2 ~ regd_str ) print $1 > str_list}' file_name 

You can also use shell redirection, like so:

awk -v regd_str="$reqd_str" 'BEGIN { FS ="|" }{ if ( $2 ~ regd_str ) print $1 }' file_name > "$str_list"

Instead of the BEGIN section , one could also use the -F option:

awk -F \| -v regd_str="$reqd_str" '{ if ( $2 ~ regd_str ) print $1 }' file_name > "$str_list"

And one could also make use of the condition { action } structure of awk..:

awk -F \| -v regd_str="$reqd_str" '$2 ~ regd_str { print $1 }' file_name > "$str_list"

Can't believe i wasted whole day to figure it out. Thanks a lot