The Magic of `grep` command

  1. Search and Find Files

    grep –i python ./
  2. Search a string Recursively in all Directories

    grep –r “function” *
  3. Searches for the entire pattern

    grep –w “RUNNING”
  4. Search and Replace All Files

    grep -lr -e 'old text' * | xargs sed -i 's/old text/new text/g'
  5. Search and Replace Specified File

    find -name myconfig_file.txt | xargs sed -i 's/old text/new text/g'
  6. Search a word in a file

    grep -c "Error" logfile.txt
  7. Case insensitive search

    grep -i "string" FILE
  8. Display N lines after match

    grep -A  "string" FILENAME
  9. Display N lines before match

    grep -B  "string" FILENAME
  10. Display N lines around match

    grep -C  "string" FILENAME
  11. Counting the number of matches

    grep -c "pattern" filename

Leave a Reply