Over a million developers have joined DZone.

Grep Quotes in Linux

DZone's Guide to

Grep Quotes in Linux

Grep is your friend, and a powerful tool. This article looks at some common scenarios for grep and how it is used to address them.

· DevOps Zone ·
Free Resource

Is the concept of adopting a continuous everything model a daunting task for your fast moving business? Read this whitepaper to break down and understand one of the key pillars of this model in Continuous Governance: The Guardrails for Continuous Everything.

Count line when words have been matched:

$ grep -c 'word' /path/to/file

Pass the -n option to precede each line of output with the number of the line in the text file:

$ grep -n 'root' /etc/passwd

Ignore word case:

$ grep -i 'word' /path/to/file

Use grep recursively under each directory:

$ grep -r 'word' /path/to/file

Use grep to search 2 different words:

$ egrep -w 'word1|word2' /path/to/file

Grep invert match:

$ grep -v 'word' /path/to/file

You can force grep to display output in colors, enter:

$ grep --color 'word' /path/to/file

You can limit the results count:

$ grep -m 10 'word' /path/to/file

You can match regular expression in files (Syntax: grep "REGEX" filename):

$ grep 'word1.*word2' /path/to/file
  • ? The preceding item is optional and matched at most once.
  • * The preceding item will be matched zero or more times.
  • + The preceding item will be matched one or more times.
  • {n} The preceding item is matched exactly n times.
  • {n,} The preceding item is matched n or more times.
  • {,m} The preceding item is matched at most m times.
  • {n,m} The preceding item is matched at least n times, but not more than m times.

Display N lines Around Match

Grep can display N lines after match (Syntax: grep -A <N> "string" filename):

$ grep -A 2 'word' /path/to/file

The following example prints the matched line, along with the two lines after it.

$ grep -A 2 -i 'word' /path/to/file

-C is the option which prints the specified N lines before the match.

$ grep -C 2 'word' /path/to/file

Are you looking for greater insight into your software development value stream? Check out this whitepaper: DevOps Performance: The Importance of Measuring Throughput and Stability to see how CloudBees DevOptics can give you the visibility to improve your continuous delivery process.

grep ,linux ,search ,script ,command line

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}