使用bash关联数组统计单词

int32位 posted @ Mar 22, 2016 03:55:00 PM in linux , 1480 阅读
转载请注明:http://krystism.is-programmer.com/若有错误,请多多指正,谢谢!

 

从bash 4开始支持关联数组,使用前需要声明,即

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

利用关联数组,很容易实现单词统计,源码文件wordCount.sh

#!/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
转载请注明:http://krystism.is-programmer.com/若有错误,请多多指正,谢谢!
  • 无匹配
  • 无匹配
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.

Bushra 说:
2023年4月03日 23:16

I am very enjoyed for this blog. Its an informative topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy. Explore

Bushra 说:
2023年4月03日 23:51

I am very enjoyed for this blog. Its an informative topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy. Click the Following Webpage

Bushra 说:
2023年4月08日 23:13

I high appreciate this post. It’s hard to find the good from the bad sometimes, but I think you’ve nailed it! would you mind updating your blog with more information? pressure washing services near Allison Park PA

Bushra 说:
2023年4月09日 03:30

I found your this post while searching for some related information on blog search...Its a good post..keep posting and update the information. Click the Following Webpage

Bushra 说:
2023年4月09日 05:29

Thank you again for all the knowledge you distribute,Good post. I was very interested in the article, it's quite inspiring I should admit. I like visiting you site since I always come across interesting articles like this one.Great Job, I greatly appreciate that.Do Keep sharing! Regards, See More Hints


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter