# 使用bash关联数组统计单词

int32位 posted @ Mar 22, 2016 03:55:00 PM in linux , 1400 阅读

declare -A map
map[key1]=value1
map[key2]=value2
map=([key1]=value1 [key2]=value2)
# 获取keys
keys=${!map[@]} # 获取values values=${map[@]}

#!/bin/bash
if [[ $# -lt 1 ]] then echo "Usage:$0 <filename>"
exit 1
fi
file=$1 declare -A count for word in$(grep -P -o '\b\w+\b' $file) do let count[$word]++
done
for word in ${!count[@]} do printf "%-14s%s\n"$word ${count[$word]}
done

./wordCount.sh filename

echo "Hello World! GoodBye World!" | ./wordCount.sh -

Hello         1
World         2
GoodBye       1

• 无匹配
• 无匹配
Emma 说:
2023年2月01日 20:26

Using the great tutorial provided by Krystism, it is now easy to count words in a file or from a standard stream using an associative array in bash 4. With the help of the Lab grown diamonds wordCount.sh script, one can quickly obtain the number of occurrences of each word in the file. This is a great way to analyze data and gain insights into the text files. So, if you are looking for an efficient way to analyze text files, be sure to try out the wordCount.sh script.

(输入验证码)
or Ctrl+Enter