Awk syntax to get part of a consistent regular expression

I'm sure it's easy, so apologize. In Perl, I can do something like

my $str = "foo=23"; $str ~= m/foo=([0-9]+)/ print "foo value is " . $1 

those. use parentheses in the regex to be able to refer to the match part later like $ 1, $ 2, etc. What is equivalent in awk?

+6
source share
4 answers

In GNU awk, which will be:

 $ cat tst.awk BEGIN { str = "foo=23" val = gensub(/foo=([0-9]+)/,"\\1","",str) print "foo value is " val } $ $ gawk -f tst.awk foo value is 23 

In other awk you will need to use [g] sub () and / or match () and / or substr () depending on what else you do / don't want to match. For instance:

 $ cat tst.awk BEGIN { str = "foo=23" val = substr(str,match(str,/foo=[0-9]+/)+length("foo=")) print "foo value is " val } $ awk -f tst.awk foo value is 23 

You will need the third arg of ', RLENGTH-length ("foo =")' on the substr () call if the target pattern is not at the end of the line. Make the "foo =" variable if you want, and if it itself can contain RE, it will take a few more steps.

+5
source

Also using GNU awk use the match() function and grab the groups of parentheses into an array.

 str = "foo=23" match(str, /foo=([0-9]+)/, ary) print "foo value is " ary[1] 
+4
source

Why not just use sed ?

 echo 'foo=23' | sed 's/foo=\([0-9]\+\)/foo value is \1/' 

EDIT: If you really need to use awk , you will need to use sub or gsub . See here.

+1
source

It may be a bit late for the party, but what about handling '=' as a field separator? Worked for me.

 echo foo=23 | awk -F= '{ print $1 " value is " $2 }' 
+1
source

All Articles