【问题标题】:bash how to search for a string in all files in given directory using grep command [duplicate]bash如何使用grep命令在给定目录中的所有文件中搜索字符串[重复]
【发布时间】:2018-01-29 19:21:35
【问题描述】:

到目前为止,我的代码是。我是初学者。

count=0
for f in $ls do
count+= grep -c "classes" $f
done
echo $count

【问题讨论】:

    标签: bash shell


    【解决方案1】:
    count=0
    for f in *
    do
    if [ -f "$f" ] #check if that file is regular file
    then
        count=$(($count+$(grep -c "classes" "$f")))
    fi
    done
    echo $count
    

    【讨论】:

    • grep: all: No such file or directory grep: it: No such file or directory grep: takes.jpg: No such file or directory ./script8: line 4: 0+: syntax error: operand expected (error token is "+") 0
    • all it takes.jpg 是我目录中的一个文件 + 答案应该是 13
    • 看来你也可以帮我解决这个问题stackoverflow.com/questions/45799657/…
    • grep: untitled folder: Is a directory ./script8: line 4: 8+: syntax error: operand expected (error token is "+") 8
    • 你必须说你的当前目录也有目录。 :3 已编辑答案
    【解决方案2】:

    我相信 find 将是满足此要求的最佳选择,请您尝试关注并告诉我这是否对您有帮助。

    find . -type f  -exec grep -i "test" {} + | wc -l
    OR
    find . -type f  | xargs grep -i "test" | wc -l
    

    您也可以提及您的路径来代替上面的 DOT。

    【讨论】:

    • 问题明确要求 grep
    • grep 与 find 一起使用,find 用于确保我们只在此处处理文件。
    【解决方案3】:

    随便用

    grep -R <stringToSearch> <dirName>
    

    例如在当前目录和里面的所有文件中搜索“文本”

    grep -R "text" .
    

    如果您想获取出现次数,请使用wc -l 作为管道

    grep -R "text" . | wc -l
    

    【讨论】:

    • -R = 递归搜索子目录
    【解决方案4】:
    grep -rnw <Directory_path> -e "Pattern"
    

    例如,如果你想在~/abc/xyz目录的所有文件中找到“helloWorld”,那么运行以下命令-

    grep -rnw ~/abc/xyz -e "helloWorld"
    

    要在当前目录中搜索字符串“HelloWorld”,请使用以下命令-

    grep -rnw . -e "helloWorld"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      • 2016-07-12
      • 2011-05-15
      • 1970-01-01
      相关资源
      最近更新 更多