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

前端 未结 11 971
心在旅途
心在旅途 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 10:41

    #!/usr/bin/env bash
    
    declare -A map 
    words="$1"
    
    [[ -f $1 ]] || { echo "usage: $(basename $0 wordfile)"; exit 1 ;}
    
    while read line; do 
      for word in $line; do 
        ((map[$word]++))
      done; 
    done < <(cat $words )
    
    for key in ${!map[@]}; do 
      echo "the word $key appears ${map[$key]} times"
    done|sort -nr -k5
    

提交回复
热议问题