在不使用命令的情况下计算shell中文件中单词的出现次数

时间:2017-12-14 10:06:13

标签: shell

下面是我的代码,但它没有按我想要的输出。 我想打印单词及其出现次数如下: anish 3 manish 4

 echo -n "ENTER FILE NAME:"
    read file
    while read -r -a word <$file; do
    if [ $# -ne 1 ] 
    then
        for word in $line; do
         # echo " $word = ${#word[*]}"

p=0    
                done


echo "$word = ${#word[*]}"


 fi

break


done

1 个答案:

答案 0 :(得分:0)

如果你可以使用更强大的shell,比如bash,你可以这样做:

$ declare -A words    # an associative array, not POSIX

$ while read word; do let "words[$word]++"; done <<END
anish
manish
anish
manish
anish
END

$ for key in "${!words[@]}"; do echo "$key ${words[$key]}"; done
manish 2
anish 3