Filter with grep

Don’t fear the Terminal

Learning Unix commands is a really useful for our sanity as developers. It’s often quicker to use terminal than using a GUI.

Searching / Filtering

Sometimes when running Unix commands we can get a huge amount of output that is overkill for what we need. It’s possible to filter that output by piping the output directly into the grep command.

Simple example

If we are wanting to find a file in a particular directory we might do something like this

~$ ls ~/Downloads

If your Downloads folder is like mine, then this is going to return a huge list of results. If I know part of the file name I am looking for I can filter the output list this

~$ ls ~/Downloads | grep Sauce

This will return all files with the name Sauce in the filename.

It’s worth noting that grep is case sensitive.

Another example

Today I needed to find a particular name of a Phoenix route. I could have just run the following command to list all routes - mix phx.routes. The problem is the project is quite large and has a large number of routes in it now, I’d have ended up having to scroll through irrelevant content. Instead I filtered the output with grep

~$ mix phx.routes | grep unprocessed

  unprocessed_counts_path  GET     /unprocessed_count/new  ProjectWeb.UnprocessedCountsController :new
  unprocessed_counts_path  POST    /unprocessed_count      ProjectWeb.UnprocessedCountsController :create

Now I know the route name I wanted was unprocessed_counts_path

Quick note on Piping |

There are lots of other commands you can pipe output from commands into. For example sort. You can even chain pipes together.

It’s worth learning more about the pipe (|).

John Polling

Developer, tinkerer, occasionally useful