Home Using Grep to find files
Post
Cancel

Using Grep to find files

The grep utility can be used to find files contains occurrences of the given pattern.

1
$ man grep

Add colors

There is an option to have matching text to be marked up. It’s nice to have it each time automatically. So it can be done by defining alias:

1
alias grep='grep --color'

Find files

To find all files contains occurrences of the pattern ‘vi[m]?’ at the end of a line:

1
$ grep -rEi 'vi[m]?$' .

Where:

  • -r — recursively
  • -E — extended regular expression
  • -i — case insensitive matching

To print line numbers and show context surrounding match:

1
2
3
4
5
6
7
8
9
10
11
$ grep -rEin -C1 'vim$' .
--
./vim-clipboard.md-12-
./vim-clipboard.md:13:vim
./vim-clipboard.md-14-:h registers
--
--
./vim-clipboard.md-35-bash
./vim-clipboard.md:36:$ brew install vim
./vim-clipboard.md-37-
--

Where:

  • -n — print line number
  • -C — show context

To print only filenames:

1
2
$ grep -rl 'vim$' .
./vim-clipboard.md

Duplicates were removed

Where:

  • -l — show only names of files

To find all files not containing string:

1
$ grep -rL 'vim' .

Where:

  • -L — show only names of files not containing string

More useful options:

  • -I — ignore binary files

Combine commands

It’s possible to combine results and provide them into other tools using pipes.

For example to execute rm command for each file in search results:

1
$ grep -r 'string' . | xargs rm

This will remove all files contained ‘string’ pattern in current directory.

If file name contains spaces, here is a trick for macOS:

grep -r 'string' . | tr '\n' '\0' | xargs -0 rm

To open result files in Vim:

1
$ vim $(grep -rL 'pattern' .)

Inside vim use :bn command to open next buffer and :bp command for previous.

Summary

OptionAction
-rRecursively search subdirectories
-EExtended regular expression
-iCase insensitive matching
-wMatch whole word
-lShow only names of files
-IIgnore binary files
-nPrint line number
-CShow context
-LShow only names of files not containing string
This post is licensed under CC BY 4.0 by the author.