【问题标题】:Expanding directories to include spaces within Bash扩展目录以在 Bash 中包含空格
【发布时间】: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 非常陌生,都是通过在线课程自学的,在您进入非课程示例之前,它只能提供很大帮助。我感谢任何和所有的帮助。

【问题讨论】:

标签: bash for-loop if-statement subdirectory


【解决方案1】:

for i in $(find . -type d)

每次您看到for i in $(...) 时,很可能您都犯了一个错误。逐行迭代列表的正确方法是使用 while read 循环:

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

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 1970-01-01
    • 2019-04-14
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    相关资源
    最近更新 更多