Nerd Alert- grep for dashes

Setup: I often drop breadcrumbs for myself in programs that have lots of console output. Out of long habit, my breadcrumbs will look something like: –-->Warning: file xyz.txt not found, creating...

This is great and typically helps me quickly find what I’m looking for in a bunch of alphabet soup. When the output over long processes gets spooled into logs that might be thousands of lines long, sometimes I just want to grep specific log messages, ie., maybe just show me all of the breadcrumb messages- those with “--->” in the line.

Grep is the obvious tool to grep large text files, but specifically searching for dashes can be tough, because grep considers the dash a special character.

I love grep, but for me, constructing the regular expression can sometimes be a pain in the neck. The key to the quick way of doing this grep is to use the double dash.

The double dash signals the end of options processing. In the examples below, I’m using the -n option to print the line numbers of the lines found. With the — double dash operator, I can only have that option (and any other options) before the double dash.

Here’s two ways to look for my breadcrumbs, which in this case can be found by looking for the arrow: “--->“. The first method specifically looks for the entire arrow:

# Using example.log:
# this looks specifically for "--->", showing line numbers as well
grep -n -- ---\> example.log

I often reduce this to just look for the three dashes. The reason why is that if one forgets to escape the greater-than sign like “\>“, the target file can get overwritten. Go ahead and ask me how I know this is true and how many times I’ve rediscovered this fact. Because of that, I often just look for the 3 dashes like so:

# Using example.log
grep -n -- --- example.log

Looks funny, works really well.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *