We ramble about code, technology and life. Sometimes we actually code...

grep the world

by Kyluke McDougall on 16 February 20161 min read

grep is a wonderful tool that I think those new to Linux should really come to grips with.

Essentially, it allows you to search for strings. Simple as that. However, I recently discovered that grep can also be used to search for strings in files in folders, i.e. if you've got a folder full of text files and you're looking for one containing a specific string use grep! syntax:

grep -r 'string you're searching for' /directory/to/search/in

Here's an example of me trying to find files still containing the string "dev.journeyatrest.com" that I use in my development environment:

grep -r 'dev.journeyatrest.com' post/index.php

Or you can omit the directory and it will search in the currently active directory. -r just means recursive; so it will search through sub-directories as well. You can limit your results to display only file names using -l, e.g.:

grep -rl 'string you're searching for' /directory/to/search/in


grep -rl 'dev.journeyatrest.com' post/index.php drafts/index.php editor/auto_save.php editor/edit/index.php

You can take this further and pipe the result to sed. sed can then use the results from a "grep -rl" to replace the string you're searching for with another string, e.g.:

grep -rl 'dev.journeyatrest.com' | xargs sed -i 's/dev.journeyatrest.com/my.journeyatrest.com/g'

The syntax 's/dev.journeyatrest.com/my.journeyatrest.com/g' is simple. 's/original string/new string to replace/g'. s and g are best covered by vim tutorials.

Simple right?