SHELL PROGRAMMING - COUNTING ALPHABETS

1) How do I get the number of times the alphabet appear ?
2) How do i count frequency of 1-letter words, 2-letter words, 3-letter words till 4 letter words.

wc - c ?

Can anyone guide me on shell prograaming


text.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
a	c	e	n	o	p
a	c	e		o	p
a	c	e		o	
	c	e
	c	e
		e

sat       so       dive
sit       do       seek
dig                pole
pig                love
log
boo
Help ?
Assuming that by "alphabets" you mean "letters" (alphabets are ordered sets of letters), this could be done in many different ways, here's one, using a shell array ("lengths") to track the number of times the words of each length were encountered, and a string to combine all letters seen ("letters") which is then reprocessed with grep/sort/uniq to calculate the character frequency.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash

# process standard input
while read -a line; do
    for word in ${line[@]}; do
        len=${#word}
        lengths[len]=$((${lengths[len]}+1))

        for((j=0; j<${#word};++j)); do
            letters+=${word:j:1}
        done
    done
done

echo "character statistics:"
echo $letters | fold -w 1 | sort | uniq -c | sort -rn

echo "word length statistics:"
for i in ${!lengths[*]}; do
    echo "Found ${lengths[i]} words of length $i"
done


online demo: http://ideone.com/kqMrQ3

PS: I'm not good at shell, there's probably a simpler way
Last edited on
Thanks, a lil confused though

So how is this thing run ?

How does it read from text.txt ?

Does it work bash letter.sh ?
Last edited on
test
This looks an awful lot like homework so I won't write a complete script for you. That being said, this looks like a job for regular expressions. Here is a starting point.

To count the number of two letter words in your text file, you can do this:
cat text.txt |grep -o '\b[A-Za-z]\{2\}\b' |wc -l

To count the number of occurences of 'a' by itself, you can do this:
cat text.txt |grep -o '\b[a]\b' |wc -l

To count the number of occurances of 'a' either by itself or in words you can do this:
cat text.txt |grep -o 'a' |wc -l

Hope this helps.
it sure does, thanks

just a simple question

how do we

Have an input with a result

For instance

echo "Number of A Present : " cat text.txt .....

it doesnt seem to work
Topic archived. No new replies allowed.