Check if first character is a number with awk

How to check if the first character of a string is a number using awk. I tried below but I keep getting syntax error.

awk ' { if (substr($1,1,1) == [0-9] ) print $0 }' da.txt

      

+3


source to share


2 answers


I suggest using @ hek2mgl's solution. I have pointed out some of the problems.

Problems:

  • You have to use regex internally /..regex../

    .
  • Use ~

    instead ==

    .


Really:

awk '{ if (substr($1,1,1) ~ /^[0-9]/ ) print $0 }' file.txt

      

+5


source


I would use regex instead substr()

. This will do the trick:

awk '$1 ~ /^[[:digit:]]/' da.txt

      



Note that I am omitting print $0

as this is the default action in awk

.

+6


source







All Articles