【发布时间】:2020-06-22 14:55:35
【问题描述】:
我编写了一个代码来递归地搜索一个文件系统及其所有子目录中的单词。虽然它在大多数情况下都有效,但在搜索包含空格的文件夹时遇到问题,例如它会在目录“Bash_Exercises”中找到搜索词,而不是“Bash 练习”。我知道,从我在 Bash 中学习的课程中,它与利用 "" 来识别整个字符串有关,但是无论我把 "" 放在哪里,我似乎都无法搜索其中有空格的文件夹姓名。我想我忽略了这么小的东西,只是想要第二双眼睛。
#! /bin/bash
# Navigate to the home directory
cd /Users/michael/desktop
# Ask for word to search
read -p "What word would you like to search for? " word
echo ""
#Find all directories
for i in $(find . -type d)
do
#In each directory execute the following
#In each directory run a loop on all contents
for myfile in "$i"/* ;
do
#If myfile is a file, not a directory or a shell script, echo the file name and line number
if [[ -f "$myfile" ]]; then
#Store grep within the varible check
check=$(grep -ni "$word" "$myfile")
#Use an if to see if the variable "check" is empty, indicating the search word was not found
if [[ -n $check ]]; then
#If check is not empty, echo the folder location, the file name within the folder, and the line where the text shows up
echo "File location: $myfile"
echo "$check"
echo ""
echo "------------------------"
echo ""
fi
fi
done
done
作为一个参考框架,我对 Bash 非常陌生,都是通过在线课程自学的,在您进入非课程示例之前,它只能提供很大帮助。我感谢任何和所有的帮助。
【问题讨论】:
-
所以你正在重新发明
grep -r? -
ShellCheck 指出您的
for i in $(find . -type d)循环在这方面很脆弱,您应该使用while read 循环来消耗查找输出 -
正如@KamilCuk 所说,从功能上讲,您可以简单地使用
grep -r <word> directory在该子目录树下的任何文件中查找单词。如果您尝试将此作为练习:) 那么还有其他有趣的方法
标签: bash for-loop if-statement subdirectory