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?
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.
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]+$/'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With