首页 > 解决方案 > 如何编写一个 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/Documents/”是作为参数给出的目录的完整地址,它也是我的 bash 脚本“ myscript.sh ”所在的文件夹。

我的脚本的输出如下:


“脚本已初始化。

基目录的完整地址:/home/myuser/Documents/

要分析的文本文件如下:

./README.txt

./TestFiles/test.txt

./TestFiles/names.txt

文件名:/home/myuser/Documents/

此文件中的字数:wc

脚本完全执行。”


我找不到什么问题。也许它是我作为参数提供的目录地址,也可能是我的脚本的逻辑。我在这里迷路了,感谢您的帮助。

标签: bashshellubuntu

解决方案


为什么不使用简单的find和 wc -w 来计算单词?

find . -type f -exec wc -w {} \; | sort -n

推荐阅读