扩展目录以在Bash中包含空格

问题描述 投票:0回答:1

我已经编写了代码,以使用文件系统及其所有子目录递归搜索单词。虽然大多数情况下都可以使用,但是在搜索包含空格的文件夹时遇到了麻烦,例如它将在目录“ Bash_Exercises”而不是“ Bash Exercises”中找到搜索词。我知道,根据我在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还是陌生的,他们都是通过在线课程进行自学的,只有在您进入非课程示例之前,它只能提供很大帮助。感谢您提供的所有帮助。

bash for-loop if-statement subdirectory
1个回答
0
投票

for i in $(find。-type d)

[每次您看到for i in $(...)都很可能是您犯了一个错误。逐行遍历列表的正确方法是使用while读取循环:

find . -type d | while IFS= read -r i; do
   : ....
done 

但是最好使用bash和零终止列表,以防文件名中包含换行符:

find . -type d -print0 | while IFS= read -d '' -r i; do

可以在bashfaq how to read a stream line by line处找到更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.