Grep Command In Unix : Linux Basic Command

(Last Updated On: September 18, 2017)

Grep Command In Unix/Linux: Basic Command

 

Grep – associate degree Introduction:

Greep could be a command-line utility for looking out plain-text datasets for lines matching an everyday expression. Grep was originally developed for the operating system software system by Ken Thompson, however, is out there these days for all Unix-like systems. Its name comes from the disfunction command g/re/p (globally search an everyday expression and print), that has an equivalent effect: doing a worldwide search with the regular expression and printing all matching lines.

Find Syntax:

grep “literal_string” file name.

14 Examples:

1: Search for the string in a single file.

Syntax: grep “literal_string” file name

Example: $ grep “this” demo_file

2: Searching for the string in many files.

Syntax: grep “string” FILE_PATTERN.

Example: $ grep “this” demo_*

3: Case insensitive search.

Syntax: grep-i “string” FILE.

Example: $ grep -i “the” demo_file.

4: Searching for the string in many files.

Syntax: grep “lines.*empty” demo_file

  • ? The preceding item is optional and matched at the most once.
  • * 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.

5: Full words search.

Example: grep -iw “is” demo_file

6: Display N lines after the match.

Syntax: grep -A <N> “string” FILENAME.

Example: grep -A 3 -i “example” demo_text

7: Display N lines before the match.

Syntax: grep -B <N> “string” FILENAME.

Example: grep -B 2 “single WORD” demo_text.

8: Display n line around the match.

Syntax: grep -c <N> “string” FILENAME.

Example: grep -C 2 “Example” demo_text.

9: Recursively Searching.

Example: grep -r “ramesh” *

10: Invert searching.

Example: grep -v “go” demo_text.

11: Counting the number of matches.

Syntax: grep -c “pattern” filename.

Example: grep -c “go” demo_text.

12: Display only the file names which match the given pattern.

Example: grep -I this demo_*

13: Show the position of match in the line.

Syntax: grep -o -b “pattern” file.

Example: grep -o -b “3” temp-file.txt.

o = match only string

b = show position

14: Show line number while displaying the output.

Syntax: grep -n “go” demo_txt.

These are the 14 best examples for grep command in Unix.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.