Gawk matching: Difference between revisions

From wikinotes
No edit summary
No edit summary
Line 26: Line 26:
#> 0
#> 0


echo "abcdefg" | awk '{  
echo "abcdefg" | awk '{
   if(match($0, "cd")) {  
   if(match($0, "cd")) {
       print "match found";  
       print "match found";
   }  
   }
}'
}'
#> match found
#> match found
</source>
</source>
</blockquote><!-- awk match -->
</blockquote><!-- awk match -->
= match-ranges =
<blockquote>
Similar to [[sed]], awk can operate on ranges between two matches.
<syntaxhighlight lang="bash">
# print lines between 'config:' and the end of input
zpool status zroot | awk '/^config:/,/end/ { print $0 }'
</syntaxhighlight>
</blockquote><!-- match-ranges -->

Revision as of 16:28, 21 February 2022

regex

Used to filter lines, like grep.

echo '
  1920x1080
  foo
  5760x1080
' | awk '$0 ~ /[0-9]+x[0-9]+/ { print $0 }'

match

match checks for a matching string, returns char number if found, otherwise returns a 0

match($0, "searchterm")
echo "abcdefg" | awk '{var=match($0, "cd"); print var}'
#> 3

echo "abcdefg" | awk '{var=match($0, "zef"); print var}'
#> 0

echo "abcdefg" | awk '{
   if(match($0, "cd")) {
       print "match found";
   }
}'
#> match found

match-ranges

Similar to sed, awk can operate on ranges between two matches.

# print lines between 'config:' and the end of input
zpool status zroot | awk '/^config:/,/end/ { print $0 }'