Web Analytics

Pipes

Intermediate~20 min read

Pipes connect commands by sending stdout of one as stdin to the next, enabling powerful one-liners for text processing.

Common Pipelines

Output
Click Run to execute your code
Note: Use tr, sort, uniq -c, and awk to build readable pipelines.
Pro Tip: Use tee to save intermediate results while continuing the pipeline.
Caution: By default, a pipeline succeeds if the last command succeeds. Consider set -o pipefail for stricter error handling.

Common Mistakes

1) Unnecessary Use of cat

# Wrong
cat file | grep pattern
# Correct
grep pattern file

2) Losing errors in the middle

# Without pipefail, early failures may be ignored
set -o pipefail  # enable stricter pipeline status

Exercise: Top Words

Task: Read a line from stdin and output the top 3 most frequent words (case-insensitive) with counts.

Output
Click Run to execute your code
Show Solution
tr '[:upper:]' '[:lower:]' | tr -cs '[:alpha:]' '\n' |
sort | uniq -c | sort -nr | head -n 3

Summary

  • Use pipes to chain commands.
  • tee saves output while piping.
  • Consider set -o pipefail for reliability.

What's Next?

Create multi-line input blocks with Here Documents.