Linux Text Processing Cheat Sheet

Core Linux text processing commands and shell patterns for searching, filtering, editing, formatting, and analyzing text files and streams.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Overview and Core Patterns
Pipe file content into grep
cat app.log | grep ERROR

# Basic pipeline for filtering text from a file.

Search a file directly
grep ERROR app.log

# Prefer direct file arguments when possible.

Read from standard input
journalctl -u nginx | awk '{print $1, $2, $3}'

# Many text tools consume stdin naturally.

Save output and continue pipeline
grep ERROR app.log | tee errors.txt | wc -l

# Write output to a file while still passing it downstream.

Split a long pipeline across lines
ps aux 
  | grep python 
  | grep -v grep 
  | awk '{print $2, $11}'

# Use backslashes for readability.

## Line Selection and Context
Show first 20 lines
head -n 20 server.log

# Preview the top of a file.

Show last 50 lines
tail -n 50 server.log

# Read the end of a file.

Follow a log in real time
tail -f /var/log/nginx/access.log

# Watch new lines as they are appended.

Print a specific line range
sed -n '100,120p' file.txt

# Extract lines 100 through 120.

Print line range with awk
awk 'NR>=100 && NR<=120' file.txt

# Alternative line-range extraction using NR.

## Formatting and Cleanup
Squeeze repeated spaces
tr -s ' ' < input.txt

# Collapse multiple spaces into one.

Trim leading whitespace
sed 's/^[[:space:]]*//' file.txt

# Remove spaces and tabs from the start of each line.

Trim trailing whitespace
sed 's/[[:space:]]*$//' file.txt

# Remove spaces and tabs from line endings.

Wrap text to 72 columns
fmt -w 72 README.txt

# Reflow long text paragraphs.

Force hard wraps
fold -w 80 long-lines.txt

# Break long lines at a fixed width.

Recommended next

No recommendations yet.