Module lessons (2/2)
Pipelines and filters (grep and |)
One of the most powerful features of the Linux command line is the ability to connect different commands so that the output of one becomes the input for the next. This technique is accomplished using pipelines and is commonly paired with the text-filtering command grep.
Filtering Text: grep
The grep (Global Regular Expression Print) command searches for a specific string of text within one or more files and prints the matching lines:
grep "string" [file_name]Useful Options for grep
grep -i "error" server.log: Performs a case-insensitive search (ignores the difference between uppercase and lowercase, finding "Error", "error", or "ERROR").grep -n "connection" server.log: Displays the line number along with the matching line.grep -v "INFO" server.log: Inverts the search, displaying only the lines that do not contain the specified keyword.
Chaining Commands: The Pipeline |
The pipeline operator is represented by the vertical bar |. It sends the standard output of the command on the left directly to the standard input of the command on the right:
[command1] | [command2]For instance, if a log file is huge and you want to search for a specific word without printing the whole file, you can combine cat and grep:
cat logs/server.log | grep ERRORThis reads the entire server.log file with cat, but instead of printing it to the screen, it pipes the stream to grep, which filters and displays only the lines containing the word "ERROR".
Usage Examples and Common Errors
If you search for a lowercase word (e.g. "post") in a file that contains it only in uppercase (e.g. "POST"), grep will not return anything:
grep "post" logs/access.log
# Output: (no results, search is case-sensitive by default)To find the line regardless of its case, use the -i flag:
grep -i "post" logs/access.log
# Output:
# 127.0.0.1 - - [22/May/2026:10:10:00 +0000] "POST /login HTTP/1.1" 401 234If the specified file does not exist, grep will return an error:
grep "ERROR" nonexistent_file.log
# Output:
# grep: nonexistent_file.log: No such file or directoryTry it yourself
Exercise 1: Search for errors in log files
Filter the file 'logs/server.log' to extract and display only the lines containing the word 'ERROR' (case-sensitive).
Show hint
Use the grep command followed by the word to search for and the file path.
Solution available after 3 attempts
Exercise 2: Pipelines and filters
Use the cat command to read the file 'logs/server.log' and pipe (|) its output to the grep command to filter and print only the lines containing the word 'WARNING'.
Show hint
Connect cat logs/server.log to grep WARNING using the pipe '|' character.
Solution available after 3 attempts
Exercise 3: Case-insensitive search
Search for all lines containing the word 'post' (either uppercase or lowercase) in the 'logs/access.log' file using the appropriate grep flag.
Show hint
Use grep with the -i option to ignore case sensitivity.
Solution available after 3 attempts