Awk regex beginning of anchor line matches space

Parse input file through awk I ran into an anchor issue in awk.

Given the following file:

 2015
2015
test
 test

Quit with awk

$ awk '$1 ~ /^[0-9]/' file
 2015
2015

Exit with sed

$ sed -n '/^[0-9]/p' file
2015

Can someone explain the behavior that I see in awk?

Seen from

  • CentOS 7, GNU bash 4.2.46, GNU Awk 4.0.2
  • AIX 7, GNU bash 4.3.30, awk (default version on AIX) and gawk 4.0.2
+4
source share
2 answers

You will understand the difference with this awk command:

awk '/^[0-9]/' file
2015

Now awk runs on a full line, such as sed, and not just in the first field.

$1 ~ /^[0-9]/compares only the first field and since the space is the default field separator in awk, therefore the first field 2015in both lines is independent of the spaces in front of it.

+5
source

, .

awk '/^[0-9]/' file, .

:

awk '$0 ~ /^[0-9]/' file

, , $0 - .

+4

All Articles