Debian Codegraph @

wf.sh

raw symbols SCIP
1 #!/bin/bash
2 # wf.sh: Crude word frequency analysis on a text file.
3 # This is a more efficient version of the "wf2.sh" script.
4
5
6 # Check for input file on command-line.
7 ARGS=1
8 E_BADARGS=85
9 E_NOFILE=86
10
11 if [ $# -ne "$ARGS" ] # Correct number of arguments passed to script?
12 then
13 echo "Usage: `basename $0` filename"
14 exit $E_BADARGS
15 fi
16
17 if [ ! -f "$1" ] # Check if file exists.
18 then
19 echo "File \"$1\" does not exist."
20 exit $E_NOFILE
21 fi
22
23
24
25 ########################################################
26 # main ()
27 sed -e 's/\.//g' -e 's/\,//g' -e 's/ /\
28 /g' "$1" | tr 'A-Z' 'a-z' | sort | uniq -c | sort -nr
29 # =========================
30 # Frequency of occurrence
31
32 # Filter out periods and commas, and
33 #+ change space between words to linefeed,
34 #+ then shift characters to lowercase, and
35 #+ finally prefix occurrence count and sort numerically.
36
37 # Arun Giridhar suggests modifying the above to:
38 # . . . | sort | uniq -c | sort +1 [-f] | sort +0 -nr
39 # This adds a secondary sort key, so instances of
40 #+ equal occurrence are sorted alphabetically.
41 # As he explains it:
42 # "This is effectively a radix sort, first on the
43 #+ least significant column
44 #+ (word or string, optionally case-insensitive)
45 #+ and last on the most significant column (frequency)."
46 #
47 # As Frank Wang explains, the above is equivalent to
48 #+ . . . | sort | uniq -c | sort +0 -nr
49 #+ and the following also works:
50 #+ . . . | sort | uniq -c | sort -k1nr -k
51 ########################################################
52
53 exit 0
54
55 # Exercises:
56 # ---------
57 # 1) Add 'sed' commands to filter out other punctuation,
58 #+ such as semicolons.
59 # 2) Modify the script to also filter out multiple spaces and
60 #+ other whitespace.