Searching Through Files With Grep (Raspberry Pi)

Typically when using the search function in an operating system it returns just files where the titles contain the search terms. However as Raspbian is a Linux OS it contains a powerful search option within the Terminal called Grep.

Grep was created in 1974 by Ken Thompson and allows for expressions (e.g. character strings) to be searched for within plain text files. Wikipedia has a page about Grep at https://en.wikipedia.org/wiki/Grep . Plain text files may make you think, “thats just .txt files” but it is not. A lot of file types are just plain text files with different file extensions and some examples Grep can search through include:

  • .txt (text files)
  • .py (Python files)
  • .html (HyperText Markup Language files)
  • .sh (Linux shell files)
  • .json (JavaScript Object Notation files)
  • .xml (Extensible Markup Language files)

Using Grep

Grep can be used with several different options depending how on we want to search, I’ve used a few examples below.

Searching in all file types in the current directory:

grep geektechstuff *.* -i

grep_1

This would search the Terminals current working directory for any file (*.*) for the string “geektechstuff”. The -i option tells Grep to ignore the case of the string, without this it would look for geektechstuff but not Geektechstuff or gEEKTECHSTUFF.

Searching in one file type in the current directory:

grep geektechstuff *.txt -i

grep_2.png

This would search the Terminals current working directory for any txt file (*.txt) for the string “geektechstuff”. The -i option tells Grep to ignore the case of the string, without this it would look for geektechstuff but not Geektechstuff or gEEKTECHSTUFF.

Searching in all file types recursively

grep -r geektechstuff -i

grep_3.png

The -r tells Grep to search recursively through the current working directory and all sub directories.

Searching in particular file types recursively

grep -r -i –include=\*.py geektechstuff ./

grep_4.png

The –include=\*.py tells Grep to look for in all .py (Python) files for geektechstuff and ./says to start in the current working directory, with the -r making Grep work through the sub-directories recursively.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.