Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using awk to search for lines that have a number of digits

Tags:

awk

Here is file1

200
201
202
203
204
205
2001
2002
2003
2004
2005

Is there an awk oneliner that finds only lines with three digits in the the first field?

like image 464
AWE Avatar asked Nov 21 '11 13:11

AWE


People also ask

What is awk '{ print $1 }'?

I. If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

How do I find the number of fields in awk?

awk with NF (number of fields) variable. NF is a built-in variable of awk command which is used to count the total number of fields in each line of the input text.


1 Answers

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

This will match the first field ($1) against three digits only (note the forced start and stop range denoted by ^ and $). It then prints the entire line ($0). You don't need a {print $0} after the regex match, because the default action is to print the line anyway.

If you want to use the interval expression operator {} in your regex then you will need to use gawk and the --posix switch:

gawk --posix '$1 ~ /^[0-9]{3}$/' file1
like image 154
Lee Netherton Avatar answered Nov 07 '22 23:11

Lee Netherton