linuxawk

How to modify value of a variable in awk with gsub and print it out?


I try to cut out a numerical value in a specific column in a specific line. To get the column I use:

awk '/REGEX1/{for(i=1;i<=NF;++i)if($i~/REGEX2/)print $i}' $file

The output is as desired:

executionTime="120"

But I'm just interested in the numerical value. If I use

awk '/REGEX1/{for(i=1;i<=NF;++i)if($i~/REGEX2/)print $i}' $file | awk '{gsub(/[^0-9]/,""); print}')

or

awk 'BEGIN{sedcmd="sed 's/[^0-9]//g'"} /REGEX1{for(i=1;i<=NF;++i)if($i~/REGEX2/) print $i | sedcmd}' tmpfile

it works. But as soon as I try to use sub(), gsub() or gensub() within an action block it fails. For example with:

awk '/REGEX1/{for(i=1;i<=NF;++i)if($i~/REGEX2/)print gsub(/[^0-9]/,"",$i)$i}' $file

the output is 7.

What am I doing wrong?

gawk -V
GNU Awk 4.1.3, API: 1.1 (GNU MPFR 3.1.5, GNU MP 6.1.1)

Solution

  • The gsub function prints the number of substitutions made. That is why you get a number even after removing every numeric character in $i.

    You should use:

    if ($i~/REGEX2/) { gsub(/[^0-9]/,"",$i); print $i}