Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a field is an integer in awk

Tags:

awk

I am using the following script to find the number of running connections on my mongodb-server.

mongostat | awk 'BEGIN{FS=" *"}{print "Number of connections: "$19}'

But every 10 lines, $19 carries a string, denoting a field name.

I want to modify my script to print only if $19 is an integer.

I could try FS = " *[^0-9]*", but it matches columns that start with number rather than giving selective printing.

like image 864
Cheeku Avatar asked Mar 05 '15 13:03

Cheeku


1 Answers

Check if this field is formed by just digits by making it match the regex ^[0-9]+$:

$19~/^[0-9]+$/

^ stands for beginning of string and $ for end, so we are checking if it consist in digits from the beginning until the end. With + we make it match at least one digit, otherwise an empty field would also match (so a file with less fields would always match).

All together:

mongostat | awk 'BEGIN{FS=" *"} $19~/^[0-9]+$/ {print "Number of connections: "$19}'
like image 193
fedorqui 'SO stop harming' Avatar answered Oct 04 '22 02:10

fedorqui 'SO stop harming'