1

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
Мона_Сах
  • 322
  • 3
  • 12

2 Answers2

2

Avoid the for loop and use something like

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

or better

find ${PWD} -type f -exec grep -l "${pattern}" {} +
Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
Walter A
  • 17,923
  • 2
  • 22
  • 40
1

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'
sterin jacob
  • 131
  • 1
  • 9