Pipe With Grep
Part of the Fundamentals section of Coddy's Terminal journey — lesson 46 of 82.
The grep command becomes especially powerful when combined with pipes. Instead of searching within a file, you can filter the output of any command to find exactly what you need.
Imagine you want to find a specific file in a directory listing:
ls -l | grep "report"This lists all files in detail, then filters to show only lines containing "report". You get targeted results without manually scanning through everything.
Piping to grep works with any command that produces text output. To find running processes related to a specific program:
ps aux | grep "python"You can also chain grep with other commands you've learned. To count how many lines contain a specific word:
cat logfile.txt | grep "error" | wc -lThis reads the file, filters for lines with "error", then counts them. The grep flags you learned earlier work the same way in pipes — use -i for case-insensitive matching or -v to exclude matches.
Challenge
EasyThe file access.log contains web server access records. Use a pipe to filter and count how many requests resulted in a 500 error status code.
Run a single command that:
- Uses
catto readaccess.log - Pipes to
grepto filter lines containing500 - Pipes to
wc -lto count the matching lines
Hint: Chain the three commands together using the
|symbol. The grep command filters the output, andwc -lcounts the remaining lines.
Cheat sheet
The grep command can filter the output of other commands using pipes (|).
Filter directory listings:
ls -l | grep "report"Filter running processes:
ps aux | grep "python"Chain multiple commands together to filter and count:
cat logfile.txt | grep "error" | wc -lAll grep flags work in pipes, such as -i for case-insensitive matching and -v to exclude matches.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Directories
Create A DirectoryCopy A DirectoryMove And Rename A DirectoryDelete A DirectoryRecap - Directory Operations7File Content
Head And TailWord CountSort CommandUnique CommandGrep BasicsGrep With FlagsRecap - Text Detective2Navigation
Print Working DirectoryList FilesChange DirectoryAbsolute vs Relative PathsHome And Root DirectoryRecap - Find Your Way8Redirection
Standard OutputOverwrite To A FileAppend To A FileStandard InputStandard ErrorRecap - Log Builder6Wildcards And Patterns
The Star WildcardThe Question Mark WildcardBracket WildcardsCombining WildcardsRecap - Selective Operations9Piping
What Is A PipeChaining Two CommandsChaining Multiple CommandsPipe With GrepRecap - Data Pipeline