如何在bash脚本中实现grep?

时间:2016-07-30 18:46:30

标签: bash unix scripting

我正在使用目录中的grep(在for循环中)搜索文件上的字符串

for file in .* *; do 
    if [[ -f "$file" && `grep -r "$pattern" "$file"` ]]; then
    path=`pwd`/"$file"
    echo "$path"
    fi
done

2 个答案:

答案 0 :(得分:2)

避免使用for循环并使用类似

的内容
grep -l "${pattern}" ${PWD}/.* ${PWD}/*

或更好

find ${PWD} -type f -exec grep -l "${pattern}" {} +

答案 1 :(得分:1)

使用find命令。要在当前文件夹中搜索

find . -exec grep "$pattern" {} \; -print'

在特定文件夹中搜索

find /home/hduser  -exec grep "$pattern" {} \; -print'