From ea0192f7cb8a7e0f9ba9e8474a0e806ef6d94ded Mon Sep 17 00:00:00 2001 From: Johannes Stoelp Date: Wed, 13 Dec 2023 00:23:02 +0100 Subject: awk: add range pattern example inclusive/exclusive --- src/tools/awk.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'src/tools') diff --git a/src/tools/awk.md b/src/tools/awk.md index 5fc3184..96212d5 100644 --- a/src/tools/awk.md +++ b/src/tools/awk.md @@ -108,6 +108,21 @@ awk '!/^#/ { print $1 }' ``` Matches records not starting with `#`. +### Range patterns +```bash +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. +```bash +echo -e "a\nFOO\nb\nc\nBAR\nd" | \ + awk '/FOO/,/BAR/ { if (!($1 ~ "FOO") && !($1 ~ "BAR")) { print } }' +``` + ### Access last fields in records ```bash echo 'a b c d e f' | awk '{ print $NF $(NF-1) }' -- cgit v1.2.3