Print Regular Expressions in AWK

Is there a way to print a regular expression (but only the corresponding line) with AWK?

+30
bash shell awk
Mar 28 2018-11-11T00:
source share
3 answers

Yes, in awk use the match() function and give it an optional array parameter ( a in my example). When you do this, the 0th element will be the part that matches the regular expression

 $ echo "blah foo123bar blah" | awk '{match($2,"[az]+[0-9]+",a)}END{print a[0]}' foo123 
+37
Mar 29 '11 at 0:01
source share

An awk specific (as opposed to one using gawk ) implementation of the solution:

 $ echo "blah foo123bar blah" | awk 'match($0,/[az]+[0-9]+/) {print substr($0,RSTART,RLENGTH)}' $ foo123 
+15
Oct 30 '15 at 2:36
source share

I use this construct quite a bit:

  split(substr($0, match($0, /[0-9]+ [Bb]ytes/)), a, " "); print a[1]; 
0
Oct 26 '16 at 20:59
source share



All Articles