0

I'm trying to create a script that takes two parameters: a word and a character, then returns how many times the character appears in the word.

Here is my code:

#!/bin/bash
((counter=0))
for i in $1
do
if i == $2   
then
((counter=counter+1))
fi

echo $counter
done

My script returns 1 every time. I'm only versed in python, so my bash syntax is poor. Thanks in advance.

Unknown
  • 666
  • 3
  • 11
  • 23

2 Answers2

3

You should try the following simple bash code

#!/bin/bash

for ((i=0; i<${#1}; i++)); do
    [[ $2 == ${1:$i:1} ]] && ((count++))
done

echo "There's $count occurrences of $2 in $1"
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • can you explain what exactly ${1:$i:1} does? – ojblass Oct 01 '12 at 21:42
  • It's a bash _parameter expansion_ : you specify the offset to print an arbitrary length of the string. Search _Substring expansion_ : http://wiki.bash-hackers.org/syntax/pe – Gilles Quénot Oct 01 '12 at 21:45
  • It's a substring command. It looks confusing as the first arg is the name of the variable (`1`, as in `$1`), the second is the start index, and third is the length to take. – Dunes Oct 01 '12 at 21:46
  • `${v:2:3}` extracts a substring of `$v` at index 2 of length 3. – tripleee Oct 01 '12 at 21:46
  • I'm receiving this error: ./countchars: line 8: unexpected EOF while looking for matching `'' ./countchars: line 11: syntax error: unexpected end of file, nevermind, I've fixed it. – Unknown Oct 01 '12 at 22:16
0

Given that you use Bash syntax,

grep -c "$2" <<<"$1"

For POSIX shell, you need to echo or (preferably) printf the string and pipe to grep.

The shell does not decompose a token into individual characters when you loop over it (and, some argue, neither should Python actually :-) -- for i in foo simply sets i to foo.

tripleee
  • 175,061
  • 34
  • 275
  • 318