wd と呼ばれるこのスクリプトから始めました。
cat "$@" | tr -cs '[:alpha:]' '\n' | tr '[:upper:]' '[:lower:]'
| sort | uniq -c | sort -n | awk '{print $2 " " $1}' | sort
これは、任意の数のファイルを入力として受け取り、ファイル内の単語の分布を次のように出力します。
wd file1 file2
blue 2
cat 3
the 5
yes 1
現在、s と t の 2 つのオプションを追加しようとしています。■ スクリプトが stopwords という入力ファイルを取得し、それらの単語を入力ファイルから削除してから配布を行います。t は引数として数値 n を取り、上位 n 語のみを出力します。デフォルトはすべての単語です。
だから、これまでのところ私はこのスクリプトを持っています。現在、私の問題は、たとえば -t 10 オプションを使用しようとすると、ファイル 10 が見つからないというメッセージが表示されますが、ファイルではなく数値である必要があります。また、-s オプションを使用しようとすると、何も実行されず、エラーは出力されません。この質問はあまり具体的ではないことは承知していますが、何が問題なのかについてのアイデアをいただければ幸いです。
#!/bin/bash
stopwords=FALSE
stopfile=""
topwords=0
while getopts s:t: option
do
case "$option"
in
s) stopwords=TRUE
stopfile="$OPTARG";;
t) topwords=$OPTARG;;
\?) echo "Usage: wd [-s stopfile] [-t n] inputfile"
echo "-s takes words in stopfile and removes them from inputfile"
echo "-t means to output only top n words"
exit 1;;
esac
done
if [ "stopwords" = FALSE ]
then
cat "$@" | tr -cs '[:alpha:]' '\n' | tr '[:upper:]' '[:lower:]'
| sort | uniq -c | sort -nr | head -n $topwords | awk '{print $2 " " $1}' | sort
else
cat "$@" | grep -v -f "$stopfile" | tr -cs '[:alpha:]' '\n' | tr '[:upper:]' '[:lower:]'
| uniq -c | sort -nr | head -n $topwords | awk '{print $2 " " $1}' | sort
fi