How to create a frequency list of every word in a file?

前端 未结 11 958
心在旅途
心在旅途 2020-12-04 09:59

I have a file like this:

This is a file with many words.
Some of the words appear more than once.
Some of the words only appear one time.

I

11条回答
  •  [愿得一人]
    2020-12-04 11:01

    Let's use AWK!

    This function lists the frequency of each word occurring in the provided file in Descending order:

    function wordfrequency() {
      awk '
         BEGIN { FS="[^a-zA-Z]+" } {
             for (i=1; i<=NF; i++) {
                 word = tolower($i)
                 words[word]++
             }
         }
         END {
             for (w in words)
                  printf("%3d %s\n", words[w], w)
         } ' | sort -rn
    }
    

    You can call it on your file like this:

    $ cat your_file.txt | wordfrequency
    

    Source: AWK-ward Ruby

提交回复
热议问题