shell——文本操作

1. 统计文件每个单词数量

#!/bin/bash

function count()
{
        if [ $# != 1 ]
        then
                echo "Need one file parameter to work!"
                exit 1;
        fi

        # 删除标点符号和特殊字符
        tr -d '[:punct:]' < $1 | tr -d '[:cntrl:]' | \

        # 删除所有数字
        tr -d '[:digit:]' | \

        # 所有大写转换为小写
        tr '[:upper:]' '[:lower:]' | \

        # 把重复空格替换为一个空格
        tr -s ' ' | \

        # 把空格替换为换行
        tr ' ' '\n' | \

        # 把相同单词放到一起
        sort | \

        # 删除相同单词, 并进行统计
        uniq -c | \

        # 根据重复次数进行排序
        sort -rn
}

while true
do
        read -p "Enter the file path(or quit)"
        case "$REPLY" in
                [Qq]|[Qq][Uu][Ii][Tt])
                        echo "Bye"
                        exit 0
                        ;;
                *)
                        # 判断是否为普通文件,可读,内容不为空
                        if [ -f "$REPLY" ] && [ -r "$REPLY" ] && [ -s "$REPLY" ]
                        then
                                count "$REPLY"
                        else
                                echo "$REPLY can not be dealed with"
                        fi
                        ;;

        esac
done

posted on   开心种树  阅读(65)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示