Search Your Files with Grep and Regex
Tags: logging, programing, coding
Published: 2019-09-10 16:13:44

<p>To understand the grep regex combination, ask yourself a question first.  How do you search through a file?  On the surface, this might seem like sort of a silly question.</p>
<p>But somewhere between the common-sense answer for many ("double click it and start reading!") and the heavily technical ("command line text grep regex") lies an interesting set of questions.</p>
<ul>
<li>Where does this file reside?</li>
<li>What kind of file is it?</li>
<li>How big is the file?</li>
<li>What, exactly, are you looking for in the file?</li>
</ul>
<p>Today, we're going to look at one of the most versatile ways to search a file: using <a href="https://www.gnu.org/software/grep/manual/grep.html">grep</a> and <a href="https://en.wikipedia.org/wiki/Regular_expression">regex (short for regular expression)</a>.</p>
<h3>Learning Grep and Regex Teaches You a Powerful Search Technique</h3>
<p>Using this combination of tools, you can search files of any sort and size.  You can also search with extremely limited access to your environment, and if you get creative, you can find just about anything.</p>
<p>But with that versatility comes a bit of a learning curve.</p>
<p>So let's look at how to take the edge off of that and get you familiar with this file search technique.  To do that, I'll walk through a hypothetical example of trying to extract some information.</p>
<p><strong>When you're done reading, you'll understand the basics enough to search your files with grep-regex.</strong></p>
<p><img class="aligncenter wp-image-686" src="https://library.scalyr.com/2018/07/19175307/Magnifying-Glass-Over-Search-Screen.png" alt="" width="288" height="287" /></p>
<p> </p>
<p><!--more--></p>
<h3>What is Grep?  A High Level Understanding</h3>
<p>Grep (actually, "grep" — you don't capitalize it) is a <a href="https://hackernoon.com/macbook-my-command-line-utilities-f8a121c3b019">command line utility</a> originating in the Unix world.  It's since made its way onto Linux machines and even <a href="https://stackoverflow.com/questions/87350/what-are-good-grep-tools-for-windows">into the Windows world</a>.</p>
<p>What does it do?  Simple enough. Grep helps you search through files, looking for patterns.</p>
<p>Here's a template of what that looks like.</p>
<pre class="lang:sh decode:true"> grep [-options] pattern [filename]</pre>
<p>So basically, at a command line prompt, you would type "grep ford cars.txt" if you wanted to search for the text "ford" in the file "cars.txt."  The grep utility would print any matching lines right there in the console for you to review.</p>
<p>The <em>-options</em> tag is just that: it lets you supply some options.  For instance, you can tell grep to ignore the case of the characters or to put the results into a new file.</p>
<p>And that's really all there is to grep.  Its beauty lies in its simplicity and the power it gives you to do things.</p>
<h3>What Does Regex Mean?</h3>
<p>Speaking of power, let's talk about regex.</p>
<p>The term is actually, as I mentioned earlier, "regular expressions," but it's such a ubiquitous term in the programmer world that it's earned a nickname.  I don't think regex has <em>quite </em>made the English dictionary yet, but programmers know what you mean by this.</p>
<p>You'll find that programmers have a love-hate relationship with regex —as in, some programmers love them and others hate them.</p>
<p>People love regex for the power they confer on their users. Others hate them for their incomprehensibility and the confusion they create.<img class="alignright wp-image-687 " src="https://library.scalyr.com/2018/07/19175308/Pull-quote-programmers-have-a-love-hate-relationship-with-regex-300x200.png" alt="" width="383" height="255" /></p>
<h3>Alright, So What is It, Really?</h3>
<p>Like grep, it's simple enough.  Regular expressions are sequences of characters that represent patterns, and they instruct regex parsers on ways to search text and match patterns.</p>
<p>Think of a <em>much </em>simpler version of this concept: <a href="https://apus.libanswers.com/faq/2235">the wildcard</a>.  The wildcard lets you enter a search like, say, "d*g" in the dictionary and receive results that include "dog," "dig," and "dug."</p>
<pre class="lang:sh decode:true">d*g =&gt; {dig, dog, dug}</pre>
<p>Regex takes this to a whole new level.</p>
<p>You can do simple matches and wildcard searches with them.  For instance, the expression "d.*g" says the same thing as my wildcard example: match words that start with d and end with g and have stuff between them.</p>
<p>But you can get more complicated, too.  A <em>lot </em>more complicated.</p>
<pre class="lang:sh decode:true">^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$</pre>
<p>Want to hazard a guess what that does?  It matches a date in yyyy-mm-dd format from 1900 through 2099.  I mean, obviously, right?</p>
<p>It's this complexity that drives the love-hate in the programming world.</p>
<p>Expressing validation logic for a date in just 64 characters is powerful.  But good luck understanding them without significant study and memorization.  They're hard to read.</p>
<h3>Grep: a Simple, Practical Example</h3>
<p>By now, you've probably put together the grep-regex equation in your mind with its value proposition.</p>
<ul>
<li>Grep lets you search files from the command line,</li>
<li>And regex lets you do some really formidable stuff.</li>
</ul>
<p>But let's walk before we run and <strong>take a look at an example using just grep</strong>.</p>
<p><img class="size-full wp-image-2924 alignright" src="https://library.scalyr.com/2017/12/08095421/You-have-a-more-powerful-option.png" alt="" width="300" height="300" />A lot of hosted solutions using Apache feature something called <a href="https://en.wikipedia.org/wiki/Webalizer">the Webalizer</a>.  It offers a very specific sort of <a href="https://www.scalyr.com/blog/what-is-log-aggregation-and-how-does-it-help-you/">log aggregation</a>, but that's not of interest for this example.</p>
<p>Instead, we're interested in its configuration file, webalizer.conf.  For this example, I want to log in to my hosted web server and figure some things out about my configuration.</p>
<p>A lot of people default to popping open a file in a text editor to take a look around and search.  But recall the restrictions I mentioned at the beginning of the post.</p>
<ul>
<li>The file resides on a server where I have limited SSH access and can't use a graphical text editor.</li>
<li>I don't know exactly what's in it, and it could be <a href="https://www.scalyr.com/blog/log-file-too-big-what-should-i-do/">really big, for all I know</a>.</li>
<li>I might need to adjust my search as I go.</li>
</ul>
<p>So because of these restrictions, I go with grep.</p>
<p>I know that I can use it from the command line to search the file.  Now, let's say that a Google search for some problem told me that I needed to check on a series of settings that start with "All" and I don't really know where in the file they are.</p>
<p>Grep to the rescue.</p>
<pre class="lang:sh decode:true">grep All webalizer.conf</pre>
<p><img class="alignnone wp-image-688 size-full" src="https://library.scalyr.com/2018/07/19175308/Grep1.jpg" alt="" width="568" height="149" /></p>
<p>That's <em>pretty </em>good, but I don't really care about those comments or "HideAllSites," so I revise it just a touch.</p>
<pre class="lang:sh decode:true">grep "#All" webalizer.conf</pre>
<p>(The quotes are because I want to search for the special character "#" as well)</p>
<p><img class="alignnone size-full wp-image-689" src="https://library.scalyr.com/2018/07/19175308/grep2.jpg" alt="" width="231" height="102" /></p>
<p>Pretty handy!  Now I'm seeing only the lines immediately of interest to me.</p>
<h3>Grep Regex: a Simple, Practical Example</h3>
<p>Alright, now we're making progress.  I've got just the settings that I want.  And I can also see that my problem may stem from the fact that the settings are not enabled, by virtue of the "#" commenting them out.</p>
<p>But let's say that for this hypothetical example, I wanted to drill in a little further.  And let's also say that the file were a lot bigger with a lot more matches, so simply opening it and looking for these lines weren't feasible.</p>
<p>What if I wanted to narrow this down to just the "yes" entries?</p>
<p>Huh.</p>
<p><strong>I've pretty much reached the limit of what I can do with simple search.</strong>  Not only is there indeterminate text between the #All and the yes/no, but there's also a variable number of spaces.  Let's further say that I'm only interested in the existence of a "yes," not a "no" or a hypothetical blank.</p>
<p>How would I do that?</p>
<p>Well, I'd get ready to <strong>start using regex</strong>.  (And I'd also test them with <a href="https://regexr.com/">this tool</a> because regex is <em>hard.</em>)  Let's see what happens with this one.</p>
<pre class="lang:default decode:true">grep "#All.*yes" webalizer.conf</pre>
<p><img class="alignnone wp-image-690 size-full" src="https://library.scalyr.com/2018/07/19175309/grep3.jpg" alt="" width="172" height="36" /></p>
<p>Success!</p>
<p>Now we've narrowed it specifically to the items that we want action with, but that are commented out.</p>
<p>As you can see, this is extremely powerful.  I've just scratched the surface, and delving any more into grep (and <em>especially</em> into regex) would carry us well beyond the scope of this post.  But even with access only to the command line, and without ever opening a file, you can perform remarkably sophisticated searches to zero in on issues.</p>
<h3>Some Additional Grep/Regex Examples</h3>
<p>Before closing, I'll leave you with some additional, quick examples to help you wrap your head around the idea further.</p>
<ul>
<li>grep "^#All" webalizer.conf searches for any line with "#All" at the beginning of the line.</li>
<li>grep "yes$l" webalizer.conf searches for any line that ends with "yes".</li>
<li>grep "^$" webalizer.conf will see if webalizer has any blank lines.</li>
<li>grep "[0-9]\{3\}-[0-9]\{4\}" contacts.txt searches contacts.txt for phone numbers.</li>
<li>grep "home|mobile" contacts.txt searches for any line that has either the word "home" or the word "mobile".</li>
</ul>
<p>Hopefully, these examples give you an idea of just how versatile these types of searches are.  This isn't intended to be comprehensive, but rather to help you come away with an idea of all you might do.</p>
<h3>Grep and Regex: Know When to Say When</h3>
<p><img class="size-medium wp-image-691 alignleft" src="https://library.scalyr.com/2018/07/19175309/Pull-quote-you-can-perform-remarkably-sophisticated-searches-to-zero-in-on-issues-300x234.png" alt="" width="300" height="234" />I'll close with a bit of philosophical advice.  As you learn your way around these tools, you'll find yourself able to do some truly cool stuff.  They'll help you solve problems and be productive.</p>
<p>But don't let yourself lose sight of the forest for the trees.</p>
<p>In a pinch (like my hypothetical one) where you need to log into a server, drill into some configuration file, and find stuff in it, this is great.  If you find yourself doing similar things on a routine basis, you might start to ask yourself why.</p>
<p>And if this is your life—grepping and regexing your way through countless, massive files (e.g., log files), then you probably have <a href="https://www.scalyr.com/product/log-aggregation">better options at your disposal</a>.</p>
<p>Grep and regex are powerful, but so too are tools dedicated to automatic ingestion, parsing, and analysis of common types of files.</p>
<p>And, since we're all in the business of automating, if you find yourself constantly slinging grep and regex at various files, you might ask yourself if there isn't a way to automate what you're doing instead.