njl.io

grep

This page serves as a reminder for performing common, simple actions with grep.

How to search for a string within a file or files

You can use grep to search for a string within a file by using this command. In this example we’re searching for “foo” in the file of bar.txt.

grep foo bar.txt

This command will search for the string “foo” in all the files in the directory foobar.

grep foo foobar/*

You can also search recursively. This command will search for the string “foo” in all files and subdirectories' files of foobar.

grep -r foo foobar

You can search recursively while ignoring some directories by using this command. This will search for the string “foo” in all of the files and subdirectories' files expect the subdirectory, “directory-to-ignore”.

grep -r --exclude-dir='directory-to-ignore' foo foobar 

Using grep to search insensitive to case

You commonly need to search without case, for example if you’re trying to find errors in logs you may want to include “Error”, “error”, and “ERROR”. You can use the -i flag to tell grep to search without case. The following command with search “file.log” for error insensitive to case.

grep -i error file.log