aboutsummaryrefslogtreecommitdiff
path: root/challenge-099/abigail/bash/ch-2.sh
blob: d01068d1ad06ede8e1888b1c9164ad316e1ee02d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/bin/sh

#
# See ../README.md
#

#
# Run as: bash ch-2.sh < input-file
#

#
# Recursively count matches:
#   - If either the string or the pattern is empty, there are no matches.
#   - Else, + count the matches if we don't match at the first character
#             if the string.
#           + if the first character of the string equals the first
#             character of the pattern:
#             o  add 1 if the pattern is just one character long
#             o  else, add the number of matches starting from the
#                then next character in the string, and the next
#                character in the pattern.
#

#
# Note that we do not have lexical variables in bash, so we're
# using a global count variable.
#
function matches () {
    # 
    # $1: string
    # $2: pattern
    #
    if   ((${#1} && ${#2}))
    then matches "${1:1}" "$2"
         if   [ "${1:0:1}" == "${2:0:1}" ]
         then if   ((${#2} == 1))
              then ((count ++))
              else matches "${1:1}" "${2:1}"
              fi
         fi
    fi
}

while read string pattern
do    count=0
      matches $string $pattern
      echo $count
done