Skip to main content

Command Palette

Search for a command to run...

[Day 3] Linux Basics - find, grep, Pipe, Redirection

Updated
3 min read

1. Redirection (> vs >>)

Both redirect command output to a file, but they handle existing content differently.

  • >Overwrite (truncates the file, then writes). Same as C's fopen("w")

  • >>Append (adds to the end of the file). Same as C's fopen("a")

echo "first" > log.txt    # log.txt contains "first"
echo "second" > log.txt   # log.txt contains "second" (first is gone)
echo "third" >> log.txt   # log.txt contains "second\nthird"

Under the hood, this connects to what I learned about fork/exec — the shell opens the file with either truncate or append mode before redirecting stdout to it.

2. find — Search by File Name

find [where] -name "pattern"
  • Uses * wildcard for pattern matching

  • Always wrap the pattern in quotes — otherwise the shell expands * before find sees it

find ~/practice -name "*.c"     # Find all .c files
find ~/practice -name "*.log"   # Find all .log files
find ~/practice -name "*.sh"    # Find all shell scripts

Key point: find searches by file name, not file content. For searching inside files, use grep.

3. grep — Search Inside Files

grep "search_term" [file]
Option Stands for Description
-r recursive Search all files in directory and subdirectories
-v invert Exclude lines that match
-i ignore case Case-insensitive search
-n number Show line numbers
grep "ERROR" error.log           # Find "ERROR" in a specific file
grep -r "printf" ~/practice/src/ # Search all files under src/
grep -v "grep"                   # Exclude grep itself from results

4. Pipe (|) — Connect Commands

Pipe sends the stdout of the left command into the stdin of the right command. Essential when the data you want to search doesn't exist as a file on disk.

ps aux | grep "bash"    # Find bash-related processes

> vs | — Don't Mix Them Up

  • > → sends output to a file

  • | → sends output to another command

I made this mistake: find . -name "error.log" > grep "ERROR" — this created a file literally named grep instead of piping to the grep command.

Chaining Multiple Pipes

Pipes can be chained to build a processing pipeline:

ps aux | grep "docker" | grep -v "grep" | wc -l

This does: list all processes → filter for "docker" → remove grep itself → count the lines.

Why grep -v "grep"? When you run ps aux | grep "docker", the grep process itself is also running and shows up in the ps output. So you get one extra false match. grep -v "grep" removes that.

5. Useful Combinations

# Extract errors from a log and save to a new file
grep "ERROR" error.log > errors_only.txt

# Count how many .sh files exist
find ~/practice -name "*.sh" | wc -l

# Count processes for a specific user (excluding grep itself)
ps aux | grep "frog" | grep -v "grep" | wc -l

Tomorrow: Linux file system structure, systemd, services, and logs.

13 views