Grep Command (Linux)


The other day, i needed to look for a string recursively in my directory structure – but only in in files with .py extension. (because there were other subfolders containing images etc, which i wanted to ignore).

  • It seems grep has an option for that : –include

Options I find useful:

[1]  -r : Read all files under each directory, recursively, following symbolic links only if they are on the command line

[2] -i : Ignore case distinctions in both the PATTERN and the input files

[3] -n : Prefix each line of output with the 1-based line number within its input file

[4] -a : Process a binary file as if it were text

[5] -l : Suppress normal output; instead print the name of each input file from which output would normally have been printed.

[6] -h :  Suppress the prefixing of file names on output.  This is the default when there is only one file (or only standard input) to search

Example using a zip directory:

$ unzip -l

$ unzip -d _RawData

$ grep -rinal India _RawData

$grep India _RawData/900.csv _RawData/924.csv  Note: am searching for word containing substring India in 2 files

Tips :

[1]   For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match.

  • grep -B 3 -A 2 foo README.txt

If you want the same number of lines before and after you can use -C num.

  • grep -C 3 foo README.txt

This will show 3 lines before and 3 lines after.

[2]    egrep




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s