From 4823b8018688092416b3cd4ba9f4f7f86789eedd Mon Sep 17 00:00:00 2001 From: johannst Date: Tue, 12 Dec 2023 23:48:13 +0000 Subject: deploy: 4ed29d46d45a751071d89be37c87de71204efda4 --- tools/awk.html | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) (limited to 'tools/awk.html') diff --git a/tools/awk.html b/tools/awk.html index efd30b7..3da3746 100644 --- a/tools/awk.html +++ b/tools/awk.html @@ -90,7 +90,9 @@ - + @@ -213,6 +215,10 @@ record ----> ∀ pattern matched fields ----> run associated action

Any valid awk expr can be a pattern.

+

An example is the regex pattern /abc/ { print $1 } which prints the first +field if the record matches the regex /abc/. This form is actually a short +version for $0 ~ /abc/ { print $1 }, see the regex comparison operator +below.

Special pattern

awk provides two special patterns, BEGIN and END, which can be used multiple times. Actions with those patterns are executed exactly once.

@@ -263,6 +269,15 @@ but this is a function and return value can be assigned to a variable.

  • %T alias for %H:%M:%S
  • +
  • +

    S ~ R, S !~ R

    +

    The regex comparison operator, where the former returns true if the string +S matches the regex R, and the latter is the negated form. +The regex can be either a +constant +or dynamic +regex.

    +
  • Examples

    Filter records

    @@ -274,6 +289,18 @@ prints the whole record.

    awk '!/^#/ { print $1 }' <file>
     

    Matches records not starting with #.

    +

    Range patterns

    +
    echo -e "a\nFOO\nb\nc\nBAR\nd" | \
    +    awk '/FOO/,/BAR/ { print }'
    +
    +

    /FOO/,/BAR/ define a range pattern of begin_pattern, end_pattern. When +begin_pattern is matched the range is turned on and when the +end_pattern is matched the range is turned off. This matches every record +in the range inclusive.

    +

    An exclusive range must be handled explicitly, for example as follows.

    +
    echo -e "a\nFOO\nb\nc\nBAR\nd" | \
    +    awk '/FOO/,/BAR/ { if (!($1 ~ "FOO") && !($1 ~ "BAR")) { print } }'
    +

    Access last fields in records

    echo 'a b c d e f' | awk '{ print $NF $(NF-1) }'
     
    -- cgit v1.2.3