bash - 如何使用 bash 从文本文件创建词汇表?
问题描述
我对 bash 完全陌生,正在尝试练习各种简单的任务。如果给定一个文本文件,我如何输出文件中的单词及其频率?例如,如果文本文件包含“我真的很喜欢汉堡”,则输出应如下所示:
汉堡 1
我 1
爱 1
真的 2
我什至不确定如何开始。如何将文本文件加载到 bash 中?你怎么放东西?对不起,非常初学者的问题,但我真的很感激一些帮助,谢谢!
解决方案
你可以通过这种方式做你想做的事:
- 获取输入文本文件
- 获取输入目录以在其中保存单词文件
- 打印带有频率的独特单词。
#!/bin/bash
echo -e "Suggested files: \n"
ls
echo -e "\n"
read -p "Enter the file name :" file
if [ -e $file ]
then
if [ -s $file ]
then
echo -e "Enter the directory where do you want to save the file in \n"
read dir
words=$(grep -v '^$' $file|tr " " "\n"|sort|uniq)
grep -v '^$' $file|tr " " "\n" |sort| grep -v '^$' > $dir/file[$j].sorted
for i in $words
do
num=$(grep -c "$i" $dir/file[$j].sorted)
echo -e "The word \e[1;33m$i\e[0m exists \e[1;34m$num\e[0m times in the file \n"
done
else
echo "The file you have entered is empty"
fi
else
echo "The file you have entered does not exist"
fi
推荐阅读
- c# - 根据条件在列表中保留不同的值
- php - 为什么正则表达式模式没有在 url 重定向中给我正确的输出?
- jquery - 如何获取嵌套在 jQuery Typeahead Search 中的 asp:TextBox 元素的值使用 .NET
- php - Laravel查询同一张表上的嵌套关系
- mysql - 正则表达式匹配复杂子字符串
- html - 如何根据菜单选择在母版页的内容部分显示不同的内容 html 页面
- ios - MPRemoteCommandCenter 未接收命令触发器
- sql-server - 如何保护 SQL Server 数据库不被意外删除?
- javascript - 用按钮绑定变量的更有效方法?
- maven - 调试 jbpm 进程