Phase 2Master bash

#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.

Search for a word in a file
$ 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:

Recursive search
$ grep -r "TODO" .
./projects/app.js:// TODO: add validation
./notes.txt:TODO: finish the report

find -- Find files

The find command searches for files and directories based on various criteria: name, type, size, modification date...

Search by name
$ find . -name "*.txt"
./notes.txt
./Documents/report.txt

The -type d option restricts the search to directories only:

Search for directories
$ find . -type d
.
./Documents
./projects

wc -- Count

wc (word count) counts lines, words, and characters in a file:

Count lines, words, characters
$ wc notes.txt
  3  12  65 notes.txt
# 3 lines, 12 words, 65 characters

The -l option displays only the number of lines:

Count lines only
$ wc -l notes.txt
3 notes.txt

Pipes | -- 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.

Filter with a pipe
$ ls | grep txt
notes.txt

Here, ls lists the files, and grep txt filters to keep only those containing "txt".

Count with a pipe
$ cat notes.txt | wc -l
3

The output of cat is sent to wc -l which counts the number of lines.

Summary

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 commands

Your turn

Try grep, find, wc, and pipes in the terminal below. Combine commands to explore the available files.

terminal — bash
user@stemlegacy:~$