Grep command

Table of Contents

————————————oc}

  • TOC

Introduction

The grep command is a powerful utility for searching for strings or patterns in text files. It stands for “global regular expression print” and is commonly used to search for specific patterns of text within a file or a set of files.

Here is the general syntax for the grep command:

grep [options] PATTERN [FILE...]
  • options: Optional flags that modify the behavior of the grep command. Some common options include -i for case-insensitive matching, -v for inverting the match, and -r for searching recursively in a directory.
  • PATTERN: The pattern or string to be searched for.
  • FILE...: The input file or files to be searched. If no file is specified, grep will read from the standard input stream.

For example, the following command will search for the word “apple” in the file fruits.txt:

grep "apple" fruits.txt

Grep or, and and not

  • grep or condition using \|

    • grep 'pattern1\|pattern2' filename
  • Grep OR Using -E

    • grep -E 'pattern1|pattern2' filename
  • Grep OR Using egrep

    • egrep 'pattern1|pattern2' filename
  • Grep OR Using grep -e

    • grep -e pattern1 -e pattern2 filename
  • Grep AND using -E pattern1.*pattern2

    • grep -E 'pattern1.*pattern2' filename
    • grep -E 'pattern1.*pattern2|pattern2.*pattern1' filename
  • Grep AND using Multiple grep command

    • grep -E 'pattern1' filename | grep -E 'pattern2'
  • Grep NOT using grep -v (This will print each line that does not contain the pattern.)

    • grep -v 'pattern1' filename
  • Print only file names that does not contain pattern (-L)

    • grep -L 'pattern' filename
  • Include/Exclude a particular file format from grep search 1:

    • grep pattern -r --include=\*.{cpp,h} rootdir
    • grep pattern -r --exclude=\*.{cpp,h} rootdir
    • To exclude directory use: --exclude-dir={abc,def}

Reference: http://www.thegeekstuff.com/2011/10/grep-or-and-not-operators

  1. https://stackoverflow.com/a/221929/2302094 




Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • Vi-Editor
  • sed command
  • find command
  • awk command
  • GitLab workflow for CMS-AN
  • Condor Jobs
  • EOS uses
  • ROOT CheatSheet
  • Mac Settings
  • Git CheatSheet
  • Bash Shell