0

我是 Bash 脚本的新手,我想制作一个脚本,该脚本将遍历目录以搜索子目录并进入其中以搜索可能位于前面提到的子目录中的文件中的特定字符串。

我目前遇到的问题实际上是第二部分。我正在尝试一一访问当前子目录中的所有文件,但它不起作用。这可能是一个愚蠢的问题,但由于我是新手,我发现自己无法找到解决问题的方法。这是代码:

if [[ $1 != "--help" ]]; 
then
    echo "counting results for string: "$1>results.txt
    let total=0

    for dir in */
    do
        if [[ -d $dir ]]; 
        then
            echo "directory: "$dir>>../results.txt
            let dirtotal=0
            cd $dir

            for i in */
            do
                if [[ -f $i ]]; 
                then
                    #look in the file i and count the number of occurrences
                    let result=`grep -c $1 $i`
                    echo $i": "$result
                    let dirtotal=$dirtotal+$result
                fi
            done

            echo "directory total: "$dirtotal>>../results.txt
            let total=$total+$dirtotal

            cd ..
        fi

    done

    echo "total: "$total>>results.txt

    exit 0

else
    display_error
    exit 1
fi

进行第二个 for...do...done 循环时会出现问题。

谢谢。

4

2 回答 2

0

您可以使用“查找”来查找文件(-type f),然后在内部搜索字符串。注意 $1 周围的双引号,使用单引号不起作用。xargs 将为在标准输出上传输的每个文件名执行一次给定命令。print0 用空字符分隔匹配项,然后指示 xargs 读取由 -0 选项以空字符分隔的行。

find /your/dir -type f -print0 | xargs -r0 grep "$1" | tee -a result.txt
于 2013-10-02T18:48:33.843 回答
0

改变

for i in */

至:

for i in *

以便它匹配除了子目录之外的文件。

此外,您应该引用所有变量,以防它们包含空格或通配符。

于 2013-10-02T17:41:14.250 回答