Nadav Peled
Nadav Peled

Reputation: 1011

bash - counting the amount of specific char in a line

Would like to know how to count a specific char in a line.
For an example :

Hey . My . Name . Is . Bash

With the char "." should return : 4

We were told grep would be usefull, but couldnt find a good way to do it.

Thanks

Upvotes: 1

Views: 126

Answers (5)

Kent
Kent

Reputation: 195079

You don't need to do it with two processes.

If you want to count special (single) char in a line:

kent$  echo "Hey . My . Name . Is . Bash"|awk '{print split($0,a,".")-1}'
4

or:

kent$  echo "Hey . My . Name . Is . Bash"|awk '{print gsub("\\.","")}'
4

Upvotes: 0

Fredrik Pihl
Fredrik Pihl

Reputation: 45662

Try:

$ echo "Hey . My . Name . Is . Bash" | grep -o '\.' | wc -l
4

Pure bash:

$ s="Hey . My . Name . Is . Bash"
$ m=${s//[^.]/}
$ echo ${#m}
4

yet another:

$ tr -C -d [\.] <<< $s | wc -c
4

Upvotes: 1

fedorqui
fedorqui

Reputation: 289795

There are many ways.

Like this for example:

$ echo "Hey . My . Name . Is . Bash" | grep -o "\." | wc -w
4

or with double grep:

$ echo "Hey . My . Name . Is . Bash" | grep -o "\."  | grep -c "\."
4

Upvotes: 1

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99921

In pure bash:

str="Hey . My . Name . Is . Bash"
len=${#str}
str=${str//./}
len2=${#str}

count=$((len-len2))

echo "There are $count '.' in '$str'"

How it works:

  • ${#var_name} expands to the length of the value of variable var_name
  • ${var_name//./} replaces all occurences of . by the empty string

Try here: http://ideone.com/SLkLkL

Upvotes: 1

aragaer
aragaer

Reputation: 17848

$ echo "Hey . My . Name . Is . Bash" | tr -cd . | wc -m

I believe using tr is cheaper here.

Upvotes: 1

Related Questions