【发布时间】:2020-06-09 23:32:45
【问题描述】:
我需要编写一个 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/*
- /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
脚本完全执行。”
我找不到问题所在。也许它是我作为参数提供的目录地址,也可能是我的脚本的逻辑。我在这里迷路了,感谢您提供任何帮助。
【问题讨论】:
-
尝试将您的代码粘贴到shellcheck.net
-
find . -type f -iname '*.txt'足以满足您的 find 命令(-type f防止包含名为mydir.txt的关闭目录)。您的for循环不会递归到子目录,但使用while read -r fname; do .. done < <(find . -type f -iname '*.txt')会。 -
另外,您只需要一个
printf "\nScript totally executed.\n\n"或一个echo -e ..而不是三个:) -
将
(wc -w $File)更改为$(wc -w $File)以防止出现错误消息“此文件中的字数:wc”。