How to implement grep in bash scripting? [duplicate]

倾然丶 夕夏残阳落幕 提交于 2020-12-13 17:57:15

问题


I am working on to search a string on files using grep in a directory(in for loop)

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

回答1:


Avoid the for loop and use something like

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

or better

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



回答2:


Use find command . To search in current folder

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

To search in specific folder

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


来源:https://stackoverflow.com/questions/38677398/how-to-implement-grep-in-bash-scripting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!