Question

I am struggling with an awk problem in my bash shell script. In the below snippet of code i am passing a variable var_awk for regular expression in awk. The idea is to get lines above a regular expression but the below echo is not displaying any data

echo `ls -ltr $date*$f* | /usr/xpg4/bin/awk -v reg=$var_awk '/reg/ {print $0}'`

I am unable to reg for regex though when i do print reg it is printing but when not doing regex as expected.

if [ $GE == "HBCA" ] || [ $GE == "HBUS" ] || [ $GE == "HBEU" ]; then
        for f in `ls -ltr $date*GEN*REVAL*log|grep -v LPD | awk '{split($9,a,"_")}{print a[3]}'`; do
                echo $f
                var_awk="$date"_RESET_CALC_"$f"
                echo $var_awk
                echo `ls -ltr $date*$f* | /usr/xpg4/bin/awk -v reg=$var_awk '/reg/ {print $0}'`
Was it helpful?

Solution

You cannot use variable in regex that way. You need to do:

/usr/xpg4/bin/awk -v reg="$var_awk" '$0~reg{ print $0 }'

or simply

/usr/xpg4/bin/awk -v reg="$var_awk" '$0~reg'
  • Inside / / your variable reg will be used as a literal word.
  • Quote your shell variables.

OTHER TIPS

try this:

...whatever you had already..|awk -v reg="$var_awk" '$0~reg'
  • it is better to wrap shell variable with quotes, e.g. if your var has spaces.
  • /pattern/ in awk is called regex constant. It cannot be used with variable, that's why it is called constant. We need to use dynamic regex here in this example.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top