Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awk - check that a field can be converted to an integer

Tags:

awk

Only print field if it can be converted to an integer

If I have this sample text file

1 cat
2 dog
3 7
4 fish5
5 22

I want my awk script to only print the field if it can be converted to an integer.

I don't want rows 1,2 and 4 to be printed.

example awk script

BEGIN {
   print "testing conversion to integer on " ARGV[1];
   myinteger = 0;  # my atmept to force this var to an integer
}
 myinteger = $2;
 myinteger != 0 { print $2; }

This doesn't work.

How can I get this to work?

like image 527
Angus Comber Avatar asked Nov 16 '12 15:11

Angus Comber


2 Answers

Awk has issues calculating strings so:

awk '$2 + 0 == $2' file.txt

3    7
5    22

This also works for me: awk '$2 + 0' file.txt

But as Ed Morton pointed out in the comments this would also include strings starting with digits then maybe this is more correct: awk '/[a-z]/{next}{print $0}' file.txt i.e. if letter in line go to next line.

like image 168
AWE Avatar answered Oct 21 '22 17:10

AWE


You can match using a pattern:

awk '$2 ~ /^[0-9]+$/'

If you want to allow negative values, you can do this:

awk '$2 ~ /^-?[0-9]+$/'
like image 44
Vaughn Cato Avatar answered Oct 21 '22 15:10

Vaughn Cato