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?
In awk, regular expressions (regex) allow for dynamic and complex pattern definitions. You're not limited to searching for simple strings but also patterns within patterns.
Any awk expression is valid as an awk pattern. The pattern matches if the expression's value is nonzero (if a number) or non-null (if a string). The expression is reevaluated each time the rule is tested against a new input record.
A regular expression enclosed in slashes (' / ') is an awk pattern that matches every input record whose text belongs to that set. The simplest regular expression is a sequence of letters, numbers, or both. Such a regexp matches any string that contains that sequence.
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With