Skip to main content

Syntax

grep [OPTIONS] PATTERN [FILE...]

Description

The grep command searches for lines containing a specified pattern. It reads from files or standard input and outputs only matching lines. This is one of the most powerful text filtering tools in Unix-like systems. Nash’s grep performs substring matching (not regex) and operates entirely within the virtual filesystem.

Options

PATTERN
string
required
The text pattern to search for. Performs literal substring matching.
-v
flag
Invert match. Show lines that do NOT contain the pattern.Alias: --invert-match
-i
flag
Ignore case distinctions. Makes the search case-insensitive.Alias: --ignore-case
-n
flag
Prefix each output line with its line number.Alias: --line-number

Examples

echo -e "apple\nbanana\napricot\ncherry" | grep ap
apple
apricot
echo -e "Apple\nBANANA\napricot" | grep -i apple
Apple
apricot

Invert match

echo -e "keep\nremove\nkeep" | grep -v remove
keep
keep

Show line numbers

echo -e "line one\nline two\nline three" | grep -n line
1:line one
2:line two
3:line three

Search in files

echo -e "error: failed\nwarning: slow\ninfo: done" > log.txt
grep error log.txt
error: failed

Combine flags

echo -e "ERROR\nWarning\nerror" | grep -in error
1:ERROR
3:error

Pipeline Examples

Filter process output

env | grep PATH
PATH=/usr/local/bin:/usr/bin:/bin

Multi-stage filtering

ls -la | grep txt | grep -v test
Shows .txt files but excludes those with “test” in the name.

Count matches

cat access.log | grep "404" | wc -l
Counts how many lines contain “404”.

Extract specific records

cat users.csv | grep "@gmail.com"
Finds all rows with Gmail addresses.

Practical Use Cases

Log analysis

cat server.log | grep -i error | grep -n "database"
Find all error messages related to database, with line numbers.

Configuration validation

grep "DEBUG=true" .env && echo "Debug mode enabled"

Filter file listings

ls | grep "\.js$" | grep -v test
List JavaScript files, excluding test files.

Quick content check

grep -i "todo" *.txt || echo "No TODOs found"

Extract data fields

cat data.csv | grep "active" | cut -d, -f1,3
Find active records and extract specific columns.

Exit Status

  • 0 - At least one match found
  • 1 - No matches found
Nash’s grep uses substring matching, not regular expressions. The pattern "a.b" matches the literal string “a.b”, not “a” followed by any character and “b”.

Tips

Multiple patterns

Use multiple grep commands in a pipeline:
cat file.txt | grep pattern1 | grep pattern2

OR logic with invert

# Show lines that don't contain "skip" or "ignore"
cat file.txt | grep -v skip | grep -v ignore

Debugging pipelines

cat data.txt | grep -n error
Line numbers help identify where matches occur in the original file.
  • sed - Stream editor for text transformation
  • cut - Extract fields from lines
  • sort - Sort lines of text
  • uniq - Filter duplicate lines

Build docs developers (and LLMs) love