Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash count number of numbers

Tags:

grep

sed

awk

I have several space separated strings:

1 -2 3  
1 23 456  
apple 69 b4n4n45 gr4pe5 -420 lol 10101010101 lol
1 23 a99 99a 9a9 -1 -23 -a99 -99a -9a9 --1 --23 --a99 --99a --9a9

I would like to know the exact number of numbers in each one of these strings. For the examples above the answers should be [ 3, 3, 3, 4]. I would not like to count strings like b4n4n45 as "numbers". Only pure integer strings should be counted.

I tried using grep and regex:

$ echo $string | grep '[0-9]' | wc

but that's not working out for me. Any tips?

like image 580
Lenna Avatar asked Oct 27 '20 03:10

Lenna


People also ask

How do I count in bash?

wc. The wc command is used to find the number of lines, characters, words, and bytes of a file. To find the number of lines using wc, we add the -l option. This will give us the total number of lines and the name of the file.

How do I count the number of columns in a file in bash?

All what has left is to simply use wc command to count number of characters. The file has 5 columns.

How do you count numbers in Unix?

Wc Command in Linux (Count Number of Lines, Words, and Characters) On Linux and Unix-like operating systems, the wc command allows you to count the number of lines, words, characters, and bytes of each given file or standard input and print the result.


1 Answers

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
like image 161
RavinderSingh13 Avatar answered Sep 20 '22 15:09

RavinderSingh13