Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How do I perform alphanumeric validation for a particular column (say $2) of a file using awk?

For example I've tried:

awk -F, '{if ($10==(/[0-9a-zA-Z]/)) count+=1;} END {print count}' final.csv

I don't get any errors or a result.

share|improve this question

2 Answers 2

You can maybe do:

awk '$10 ~ /^[0-9a-zA-Z]+$/ {count++} END{print count}' file

This also works to me: to check from 0 to z, being all numbers and letters in the range.

awk '$10 ~ /^[0-z]+$/ {count++} END{print count}' file

The idea is to check if the given field ($10 in your case) is just based on a set of alphanumeric characters. This is accomplished by using ^ and $ to indicate the beginning and the end of the field.

share|improve this answer
1  
Without explicitly setting the locale, there's no way to know what is in the range [0-z] or [0-9]. Consider using a POSIX character class instead. –  Chris Down Apr 8 at 13:04
    
I see, @ChrisDown but [[:alnum:]] is not working to me either. –  fedorqui Apr 8 at 13:13
1  
@fedorqui:[:alnum:] is a GAWK feature. Non-GNUish AWKs do not have that. GNU tends to stuff lotsa features into each utility and often users of such GNUtilities forget to mention that they are NOT using the classical utilities with the same name. GNU causes lots of such confusion... –  yeti Apr 8 at 13:40
1  
@yeti: that is not correct, see the other comment.. –  Scrutinizer Apr 8 at 14:20
1  
@fedorqui I think there should be a + sign instead of a * Otherwise empty fields count as alphanumeric –  Scrutinizer Apr 8 at 14:51

Something like this should work:

awk -F, '$10 ~ /^[[:alnum:]]+$/ { count++ } END{ print count+0 }'
share|improve this answer
1  
Please underline that you are using GAWK. Original AWKs do not have [:alnum:] and friends. –  yeti Apr 8 at 13:37
3  
@yeti Yes they do. Any Posix compliant awk knows this.. –  Scrutinizer Apr 8 at 14:17
    
+1. I also prefer print count+0 to report a zero count when no matches are found (nothing is printed in this situation when print count is used –  1_CR Apr 8 at 15:37
    
@1_CR That's a good idea, thanks. –  Chris Down Apr 9 at 2:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.