bash - 如何编写一个 bash 脚本来递归计算每个文档中的单词数?
问题描述
我需要编写一个 bash 脚本,它将递归地查找作为参数给出的目录下的所有文件,并计算每个文档中的单词数。
到目前为止我尝试过的代码如下所示,但它不起作用:
#!/usr/bin/env bash
echo "Script initialized."
# Putting on a variable the address given as an argument:
BaseDirectory=${1}
echo ""
echo "Full address of the base directory: $BaseDirectory"
echo ""
# Finding (recursively) all the *.txt files from the directory this script is being executed:
echo "Text files to be analyzed are the following:"
find . -iname '*.txt' -exec echo "{}" \;
echo ""
for File in $BaseDirectory
do
echo "File name: $File"
NumberOfWords=(wc -w $File) #Counting the words present in the file
echo "Number of words within this file: $NumberOfWords"
echo ""
done
echo ""
echo "Script totally executed."
echo ""
read -p "Press [ENTER] to close this window."
我正在使用Ubuntu 终端通过以下命令行执行脚本: sudo bash myscript.sh /home/myuser/Documents/
我尝试过的其他文件夹地址包括:
- /home/myuser/文档/*
- /home/myuser/Documents/*.txt
- /*
等等...
其中“/home/myuser/Documents/”是作为参数给出的目录的完整地址,它也是我的 bash 脚本“ myscript.sh ”所在的文件夹。
我的脚本的输出如下:
“脚本已初始化。
基目录的完整地址:/home/myuser/Documents/
要分析的文本文件如下:
./README.txt
./TestFiles/test.txt
./TestFiles/names.txt
文件名:/home/myuser/Documents/
此文件中的字数:wc
脚本完全执行。”
我找不到什么问题。也许它是我作为参数提供的目录地址,也可能是我的脚本的逻辑。我在这里迷路了,感谢您的帮助。
解决方案
为什么不使用简单的find和 wc -w 来计算单词?
find . -type f -exec wc -w {} \; | sort -n
推荐阅读
- java - 从子类调用方法
- pandas - 熊猫数据框中的可点击链接
- regex - 在 shell 中运行正则表达式 --> 无效选项
- c++ - 物体在两帧中的运动
- javascript - javascript 正则表达式 - 从输出中删除多余的斜杠
- python - 无法使用 Selenium 单击/悬停在 href 按钮上
- html - 每个子目录的 ios 书签图标
- android - 错误:找不到符号变量 toast
- mongodb - 如果使用节点红色函数节点从嵌套文档中匹配键值对,则查找 mongodb 文档
- c++ - 我想获取我在 C++ 中创建的每个进程的 PID,并在特定时间后终止每个进程