DEV Community

Cover image for Living in the Shell #3; grep (Pattern Matching) (Part 2)
Babak K. Shandiz
Babak K. Shandiz

Posted on • Originally published at babakks.github.io on

3 2

Living in the Shell #3; grep (Pattern Matching) (Part 2)

grep🎖️

Prints/filters lines that match a Regular Expression (RE) pattern.

Print line numbers -n

echo -n 'Hello World!\nI''m Going!\nGoodbye!' | grep -n "G."
Enter fullscreen mode Exit fullscreen mode
  2:Im Going!
  3:Goodbye!

Print lines around (after/before) every match -A -B

cat ~/.bashrc | grep "if" -A 5 -B 1
Enter fullscreen mode Exit fullscreen mode

Prints next 5 lines and previous 1 line when caught any "if".

Only check silently (no output) -q

cat ~/.bashrc | grep -q "alias"
Enter fullscreen mode Exit fullscreen mode

Returns with 0 exit code on any match, otherwise 1.

Count matching lines -c

cat ~/.bashrc | grep -c "alias"
Enter fullscreen mode Exit fullscreen mode

Print only matching substring -o

echo -n 'Hello World!\nI''m Going!\nGoodbye!' | grep -o "G..d"
Enter fullscreen mode Exit fullscreen mode
  Good

Top comments (1)

Collapse
 
ayaanraj profile image
ayaanraj

grep with substring is awesome 🤩❤

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay