shell脚本统计文件中单词的个数

本文介绍了一种使用Shell脚本处理文本的方法,包括去除标点符号、统计单词频率等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、方案

方法一:

(1)cat file|sed 's/[,.:;/!?]/ /g'|awk '{for(i=1;i<=NF;i++)array[$i]++;}END{for(i in array) print i,array[i]}'   #其中file为要操作的文件,sed中/ /间有一个空格。

(2)sed 's/[,.:;/!?]/ /g' file|awk '{for(i=1;i<=NF;i++)array[$i]++;}END{for(i in array) print i,array[i]}'     #(1)和(2)效果一致。

方法二:

(1)awk 'BEGIN{RS="[,.:;/!?]"}{for(i=1;i<=NF;i++)array[$i]++;}END{for(i in array) print i,array[i]}' file

二、验证

[root@hehe668 shell]# cat file
hello world,hi girl;how old are you?
where are you from?
how are you?
i am fine!thinks.
and you?
http://www.cnblogs.com/youxuguang/

[root@hehe668 shell]# cat file|sed 's/[,.:;/!?]/ /g'|awk '{for(i=1;i<=NF;i++)array[$i]++;}END{for(i in array) print i,array[i]}'
com 1
http 1
from 1
www 1
i 1
you 4
hi 1
hello 1
youxuguang 1
and 1
world 1
cnblogs 1
where 1
old 1
how 2
fine 1
am 1
are 3
girl 1
thinks 1

[root@hehe668 shell]# sed 's/[,.:;/!?]/ /g' file|awk '{for(i=1;i<=NF;i++)array[$i]++;}END{for(i in array) print i,array[i]}'
com 1
http 1
from 1
www 1
i 1
you 4
hi 1
hello 1
youxuguang 1
and 1
world 1
cnblogs 1
where 1
old 1
how 2
fine 1
am 1
are 3
girl 1
thinks 1

[root@hehe668 shell]# awk 'BEGIN{RS="[,.:;/!?]"}{for(i=1;i<=NF;i++)array[$i]++;}END{for(i in array) print i,array[i]}' file
com 1
http 1
from 1
www 1
i 1
you 4
hi 1
hello 1
youxuguang 1
and 1
world 1
cnblogs 1
where 1
old 1
how 2
fine 1
am 1
are 3
girl 1
thinks 1

原文:http://www.cnblogs.com/youxuguang/p/5917215.html

转载于:https://www.cnblogs.com/youxuguang/p/5917215.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值