In the previous post Unix shell: getting started we met base shell commands useful during application development. This time I will focus only on a one command - grep. Grep command is used to find given string in file or files.

Finding exact word in a file

Grep command it’s super easy to use if you want to just find given word (case sensitive) in a given file. Let’s say you want to find word create in your log file called user.log - you would use grep create user.log

Finding word and ignoring case

If you want to find create word but this time you want to also find uppercased version you have to pass --ignore-case option or -i which is a shortcut for this option: grep -i create user.log

Want to receive useful tips, information about new Ruby gems and articles on a daily basis? Make sure you follow me and say hello!

Using regular expressions

This is the moment when fun comes in - you can also use base regular expressions in your command. So if you want to find word create or creating in your file you may want to use this version grep creat.* user.log

Finding all lines excluding given word

If you want to find all lines where given file does not exist you have to pass --invert-match option or -v shortcut. Using grep -v create user.log will display all lines where word create does not exist.

Searching in a directory

Instead of a single file you may want to search through the whole directory, even nested directories. To achieve this you have to use -r option and then pass directory name at the end instead of single filename: grep -r create some_directory/

Options - gotta catch them all

You can combine options. Following combination would show lines where there is no word starting with create lowercased or uppercased and it would search through given directory:

grep -i -v create.* /directory_name

If you are wondering when given option starts with double dash and when with single remember this: when option name is longer than one character it requires double dash otherwise you can use a single dash - that’s why all shortcuts start with the single dash. It should be easy to remember.

Now grep some file.. sorry, I mean grab some file and start searching for strings!

Want to become a better Rails developer?
Download for free the Introduction Rails patterns book and dive into the world of refactoring and easy-testable Ruby code today.
Join over 1,000 developers already subscribed to my newsletter and download the book. You can unsubscribe anytime:

Subscribe and get the book!