7

Am sure this is easy, so apologies. In Perl I might do something like

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

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

gimmeamilk
  • 2,016
  • 5
  • 24
  • 36

4 Answers4

6

Also with GNU awk, use the match() function and capture the parenthesis groups into an array.

str = "foo=23"
match(str, /foo=([0-9]+)/, ary)
print "foo value is " ary[1]
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
5

In GNU awk that'd 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's you'd need to use [g]sub() and/or match() and/or substr() depending on what else you do/don't want to match on. For example:

$ 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'd need a third arg of ',RLENGTH-length("foo=")' on the substr() call if the target pattern isn't at the end of a line. Make "foo=" a variable if you like and if it itself can contain an RE there's a few more steps necessary.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
1

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'll have to use sub or gsub. See here.

Community
  • 1
  • 1
Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
  • Thanks, I did not realise sed could do this. – gimmeamilk Oct 21 '12 at 15:37
  • 1
    Just be aware that "+" is an ERE meta-character, and many "sed"s by default only support BREs. For a solution portable to all seds you'd need to use [0-9][0-9]* instead. – Ed Morton Oct 21 '12 at 16:05
1

Maybe a bit late for the party, but how about treating '=' as a field separator? Worked a treat for me!

echo foo=23 | awk -F= '{ print $1 " value is " $2 }'
kbro
  • 4,754
  • 7
  • 29
  • 40