Bash count number of numbers
Could you please try following(tested and written with shown samples), this should include negative numbers too, since OP has mentioned about integers so I have not considered counting floats. It gives output as 3 3 3
for mentioned 3 lines of samples.
awk '
{
for(i=1;i<=NF;i++){
if(length(int($i))==length($i)){ count++ }
}
print count
count=""
}' Input_file
Another awk:
$ awk '{for(i=1;i<=NF;i++)if($i+0||$i==0)c++;print c;c=0}' file
Output:
3
3
3
Edit: After my morning coffee I noticed pure integer strings so beware, this one counts decimal numbers also.
Bash count number of numbers
echo $string | grep -Po '(^|^-| | -)[0-9]+((?= )|$)' | wc -w
wc -w
will count the number of space separated sub-strings in a given input
We can use grep -Po
(-P for Perl regex, -o output ONLY matching) to match pure number sub-strings
We can use Regex to define a pattern of sub-strings we want to keep:
(^|^-| | -)
Starts with one of the four possible starting conditions[0-9]+
Contains only one or more integer characters((?= )|$)
Ends with a space or end of line character,(?= )
looks ahead for a space character but doesn't match, allowing overlap