How do I perform action on all matching groups when the pattern matches multiple times in a line?
To illustrate, I want to search for /Hello! (\d+)/
and use the numbers, for example, print them out or sum them, so for input
abcHello! 200 300 Hello! Hello! 400z3
ads
Hello! 0
If I decided to print them out, I'd expect the output of
200
400
0
This is a simple syntax, and every awk (nawk, mawk, gawk, etc) can use this.
{
while (match($0, /Hello! [0-9]+/)) {
pattern = substr($0, RSTART, RLENGTH);
sub(/Hello! /, "", pattern);
print pattern;
$0 = substr($0, RSTART + RLENGTH);
}
}
This is gawk
syntax. It also works for patterns when there's no fixed text that can work as a record separator and doesn't match over linefeeds:
{
pattern = "([a-g]+|[h-z]+)"
while (match($0, pattern, arr))
{
val = arr[1]
print val
sub(pattern, "")
}
}
GNU awk
awk 'BEGIN{ RS="Hello! ";}
{
gsub(/[^0-9].*/,"",$1)
if ($1 != ""){
print $1
}
}' file
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