Mad Echet
Mad Echet

Reputation: 3881

Curly braces in awk reg exp

I am trying to match a fixed number of digits using curly braces in awkbut I get no result.

# This outputs nothing
echo "123" | awk '/^[0-9]{3}$/ {print $1;}' 

# This outputs 123
echo "123" | awk '/^[0-9]+$/ {print $1;}' 

Do I need to do something specific to use curly braces?

Upvotes: 7

Views: 5273

Answers (2)

Tony Barganski
Tony Barganski

Reputation: 2291

AWK on Ubuntu 20.04.4 LTS is up-to-date, released in year 2020 of but its mawk.

As Ed Morton stated in a comment above, "mawk is a minimal functionality awk, optimized for speed of execution,...".

Seems those optimizations were at the expense of functionality.

SOLUTION
Install GNU awk (gawk):

$ sudo apt install gawk -y

$ awk -W version
GNU Awk 5.0.1, API: 2.0 (GNU MPFR 4.0.2, GNU MP 6.2.0)
Copyright (C) 1989, 1991-2019 Free Software Foundation.

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 754700

Mac OS X awk (BSD awk) works with the first command shown:

$ echo "123" | /usr/bin/awk '/^[0-9]{3}$/ {print $1;}' 
123
$

GNU awk does not. Adding backslashes doesn't help GNU awk. Using option --re-interval does, and so does using --posix.

$ echo "123" | /usr/gnu/bin/awk --re-interval '/^[0-9]{3}$/ {print $1;}' 
123
$ echo "123" | /usr/gnu/bin/awk --posix '/^[0-9]{3}$/ {print $1;}' 
123
$

(I'm not sure where mawk 1.3.3 dated 1996 comes from, but it is probably time to get an updated version of awk for your machine.)

Upvotes: 10

Related Questions