Based in Melbourne, Australia.

Developer
Life

Basics to using grep

Basics to using grep

Contents

Overview

grep is a command-line utility for searching plain-text data sets for lines that match a regular expression - displaying or exporting all matching lines.

Basic usage:

grep 'TEXT_TO_SEARCH' fileToSearch
note

The "text_to_search" can be a plain string or a regular expression.

Below are some of the most common options we can use in grep to make our lives easier:

  • -n: prints the line number
  • -o: prints only the matching part of the text
  • -c: prints the number of matches

This allows us to return everything after we match with the files in a folder directory.

grep -o 'error_message.*' /c/users/logs/*

Examples

Assume that we need to find whether the text LOGIN_FAILED has appeared in our log files. The command we would need would be as simple as the below. In this case, grep will print the lines of text which include LOGIN_FAILED.

grep 'LOGIN_FAILED' logFile.txt

Another useful way we can use grep, is to find out whether a file exists in a folder which contains thousands of other files. In here the | (pipe-delimiter) will send the output of the ls command as an input to the grep command.

ls | grep 'FILE_NAME'

Additionally, we can add a little regex to our search and return the full line grep matched on. This can be extremely useful if you are looking for a specific timestamp or customer ID across multiple files.

grep 'TEXT_TO_SEARCH.*' trace.log

Saving Results To A File

Sometimes we may be required to share logs for a specific sessionId. So how would we do this? Well luckily this is pretty simple when it comes to grep. Simple just add > (greater-than) to the end of your command and the file path and name of the file.

grep 'TEXT_TO_SEARCH.*' trace.log > result.log
HTTP Transformation - XSLT-buffer-size

HTTP Transformation - XSLT-buffer-size

Want To Learn To Hack?

Want To Learn To Hack?