My GAWK version on RHEL is:
gawk-3.1.5-15.el5
I wanted to print a line if the first field of it has all digits (no special characters, even space to be considered)
Example:
echo "123456789012345,3" | awk -F, '{if ($1 ~ /^[[:digit:]]$/) print $0}'
Output:
Nothing
Expected Output:
123456789012345,3
What is going wrong here ? Does my AWK version not understand the GNU character classes ? Kindly help
To match multiple digits in the the
[[:digit:]]
character class add a+
, which means match one or more number of digits in$1
.which satisfies your requirement.
A more idiomatic way ( as suggested from the comments) would be to drop the
print
and involve the direct match on the line and print it,Some more examples which demonstrate the same,
(and)
do NOT produce any output a per the requirement.
Another
POSIX
compliant way to do strict length checking of digits can be achieved with something like below, where{3}
denotes the match length.(and)
does not produce any output.
If you are using a relatively newer version of
bash
shell, it supports a nativeregEx
operator with the~
usingPOSIX
character classes as above, something likeFor an input file say
file
The script produces,
Although this works,
bash regEx
can be slower a relatively straight-forward way using string manipulation would be something likeThe
"${row1//[0-9]/}"
strips all the digits from the row and the condition becomes true only if there are no other characters left in the variable.