#6 Search and filter
grep, find, wc, pipes
grep -- Search for text
The grep command searches for a pattern (a word, an expression) in one or more files. It displays each line that contains the searched pattern.
$ grep "notes" file.txt
This file contains important notes.With the -r (recursive) option, grep searches through all files in the current directory and its subdirectories:
$ grep -r "TODO" .
./projects/app.js:// TODO: add validation
./notes.txt:TODO: finish the reportfind -- Find files
The find command searches for files and directories based on various criteria: name, type, size, modification date...
$ find . -name "*.txt"
./notes.txt
./Documents/report.txtThe -type d option restricts the search to directories only:
$ find . -type d
.
./Documents
./projectswc -- Count
wc (word count) counts lines, words, and characters in a file:
$ wc notes.txt
3 12 65 notes.txt
# 3 lines, 12 words, 65 charactersThe -l option displays only the number of lines:
$ wc -l notes.txt
3 notes.txtPipes | -- Chaining commands
The | (pipe) character sends the output of one command as input to the next one. It is one of the most powerful terminal concepts: combining simple tools to create complex workflows.
$ ls | grep txt
notes.txtHere, ls lists the files, and grep txt filters to keep only those containing "txt".
$ cat notes.txt | wc -l
3The output of cat is sent to wc -l which counts the number of lines.
Summary
grep "pattern" file # Search for text in a file
grep -r "pattern" . # Search recursively
find . -name "*.txt" # Find files by name
find . -type d # Find directories
wc file # Count lines, words, characters
wc -l file # Count lines
command1 | command2 # Pipe: chain commandsYour turn
Try grep, find, wc, and pipes in the terminal below. Combine commands to explore the available files.