スクリプトを使用してファイル内の単語の頻度を見つけます。

スクリプトを使用してファイル内の単語の頻度を見つけます。

私が持っているファイルはtestであり、次の行が含まれています。

This is a test Test test test There are multiple tests.

私は出力が次のようになります:

test@3 tests@1 multiple@1 is@1 are@1 a@1 This@1 There@1 Test@1

次のスクリプトがあります。

 cat $1 | tr ' ' '\n' > temp # put all words to a new line
    echo -n > file2.txt # clear file2.txt
    for line in $(cat temp)  # trace each line from temp file
    do
    # check if the current line is visited
     grep -q $line file2.txt 
     if [ $line==$temp] 
     then
    count= expr `$count + 1` #count the number of words
     echo $line"@"$count >> file2.txt # add word and frequency to file
     fi
    done

ベストアンサー1

sort | uniq -c | sort -n頻度表を作成するために使用されます。希望の形式を取得するには、さらに調整が必要です。

 tr ' ' '\n' < "$1" \
 | sort \
 | uniq -c \
 | sort -rn \
 | awk '{print $2"@"$1}' \
 | tr '\n' ' '

おすすめ記事