pipe
Pipe Command Reference
Section titled “Pipe Command Reference”Unix-style pipe chain functionality and text processing commands for data filtering, transformation, and analysis.
Table of Contents
Section titled “Table of Contents”- Overview
- Pipe Chain Syntax
- Calculator (bc)
- Text Search (grep)
- Stream Editor (sed)
- Pattern Processing (awk)
- Sorting and Deduplication
- String Manipulation
- File Operations
- Process Listing (ps)
- Word Counting (wc)
- Field Extraction (cut)
- Character Translation (tr)
- Head and Tail
- Complex Pipeline Examples
Overview
Section titled “Overview”The pipe system allows chaining multiple commands together using the | operator. Each command processes the output from the previous command, enabling powerful data transformation workflows.
Available Commands
Section titled “Available Commands”| Command | Purpose |
|---|---|
bc | Calculator with math functions |
cat | Display file contents |
grep | Search text patterns |
ls | List directory contents |
ps | List running processes |
sed | Find and replace text |
awk | Field extraction and processing |
sort | Sort lines |
uniq | Remove duplicates |
wc | Count words, lines, characters |
cut | Extract columns/fields |
trim | Remove whitespace |
tr | Translate characters |
rev | Reverse strings |
split | Split strings into arrays |
join | Join arrays into strings |
head | Display first N lines or bytes |
tail | Display last N lines or bytes |
echo | Print text |
nslookup | DNS hostname lookup |
find | Search for files |
xclip | Copy to clipboard |
decipher | Decode text |
Pipe Chain Syntax
Section titled “Pipe Chain Syntax”data | command1 args | command2 args | command3 args
- Data flows through the pipe from left to right
- Each command processes output from the previous command
- Final command returns the processed result
- All commands must be connected with pipes (|)
Basic Examples
Section titled “Basic Examples”Simple pipe: read file and count lines
Section titled “Simple pipe: read file and count lines”cat /etc/passwd | wc -l
Three-stage pipe: read, filter, count
Section titled “Three-stage pipe: read, filter, count”cat access.log | grep “error” | wc -l
Filter and sort
Section titled “Filter and sort”ls | grep “.txt” | sort
Calculator (bc)
Section titled “Calculator (bc)”Powerful calculator with arithmetic operations, mathematical functions, and special features.
Arithmetic Operations
Section titled “Arithmetic Operations”Basic arithmetic
Section titled “Basic arithmetic”5 + 3 | bc # 8 10 - 4 | bc # 6 7 * 6 | bc # 42 20 / 4 | bc # 5 17 % 5 | bc # 2 (modulo/remainder) 2 ^ 8 | bc # 256 (power)
Order of operations (follows PEMDAS)
Section titled “Order of operations (follows PEMDAS)”5 + 3 * 2 | bc # 11 (multiplication first) 2 + 3 * 4 - 5 | bc # 9 10 / 2 + 3 | bc # 8
Mathematical Functions
Section titled “Mathematical Functions”Square root
Section titled “Square root”sqrt 16 | bc # 4 sqrt 2 | bc # 1.414214
Absolute value
Section titled “Absolute value”abs -5 | bc # 5 abs 3.7 | bc # 3.7
Rounding functions
Section titled “Rounding functions”floor 3.7 | bc # 3 ceil 3.2 | bc # 4 round 3.5 | bc # 4 round 3.4 | bc # 3
Sign function
Section titled “Sign function”sign -5 | bc # -1 sign 0 | bc # 0 sign 10 | bc # 1
Trigonometric Functions
Section titled “Trigonometric Functions”Basic trig (radians)
Section titled “Basic trig (radians)”sin 0 | bc # 0 cos 0 | bc # 1 tan 0 | bc # 0
Pi constant
Section titled “Pi constant”sin pi | bc # ~0 (sin(π)) cos pi | bc # -1 (cos(π))
Inverse trig
Section titled “Inverse trig”asin 0.5 | bc # 0.523599 (π/6) acos 0 | bc # 1.5708 (π/2) atan 1 | bc # 0.785398 (π/4)
Utility Functions
Section titled “Utility Functions”Sum of numbers
Section titled “Sum of numbers”sum 1 2 3 4 5 | bc # 15
Random numbers
Section titled “Random numbers”rnd | bc # Random 0-1 rnd 10 | bc # Random 0-10
Range generation
Section titled “Range generation”range 5 | bc # [0, 1, 2, 3, 4] range 2 7 | bc # [2, 3, 4, 5, 6, 7] range 0 10 2 | bc # [0, 2, 4, 6, 8, 10]
Character Conversions
Section titled “Character Conversions”ASCII code to character
Section titled “ASCII code to character”char 65 | bc # [ A ] char 72 105 | bc # [ Hi ]
Character to ASCII code
Section titled “Character to ASCII code”code A | bc # [ 65 ] code Hello | bc # [ 72, 101, 108, 108, 111 ]
Chained Calculations
Section titled “Chained Calculations”Comma-separated chain: (10 + 5) * 2 - 3
Section titled “Comma-separated chain: (10 + 5) * 2 - 3”10 + 5, * 2, - 3 | bc # 27
Multi-step calculation
Section titled “Multi-step calculation”100 / 4, sqrt | bc # 5 (sqrt(25)) 2 ^ 4, + 10 | bc # 26 (16 + 10)
Special Features
Section titled “Special Features”Random IP address generation
Section titled “Random IP address generation”ip | bc # 192.168.1.45 ip 5 | bc # Generate 5 random IPs
Text Search (grep)
Section titled “Text Search (grep)”Search for patterns in text with various options.
Basic Search
Section titled “Basic Search”Find lines containing “error”
Section titled “Find lines containing “error””cat /var/log/system.log | grep “error”
Find lines containing “root” in passwd file
Section titled “Find lines containing “root” in passwd file”cat /etc/passwd | grep “root”
Search in file directly
Section titled “Search in file directly”cat /home/user/notes.txt | grep “TODO”
Case-Insensitive Search
Section titled “Case-Insensitive Search”-i flag for case-insensitive
Section titled “-i flag for case-insensitive”cat file.txt | grep -i “warning” cat log.txt | grep -i “error”
Matches: ERROR, error, Error, ErRoR
Section titled “Matches: ERROR, error, Error, ErRoR”cat system.log | grep -i “error”
Inverted Match (Exclude)
Section titled “Inverted Match (Exclude)”-v flag to exclude matches
Section titled “-v flag to exclude matches”cat file.txt | grep -v “debug” cat /etc/passwd | grep -v “nologin”
Show all non-comment lines
Section titled “Show all non-comment lines”cat config.conf | grep -v ”^#“
Combined Flags
Section titled “Combined Flags”Case-insensitive exclusion
Section titled “Case-insensitive exclusion”cat log.txt | grep -iv “debug”
Multiple grep stages
Section titled “Multiple grep stages”cat file.txt | grep “error” | grep -v “ignore”
Practical Examples
Section titled “Practical Examples”Find all .txt files
Section titled “Find all .txt files”ls | grep “.txt”
Find all error logs except debug
Section titled “Find all error logs except debug”cat system.log | grep “error” | grep -v “debug”
Find IP addresses in log
Section titled “Find IP addresses in log”cat access.log | grep -E “[0-9]+.[0-9]+.[0-9]+.[0-9]+“
Find users with bash shell
Section titled “Find users with bash shell”cat /etc/passwd | grep “/bin/bash”
Stream Editor (sed)
Section titled “Stream Editor (sed)”Find and replace text in streams.
Basic Substitution
Section titled “Basic Substitution”Replace first occurrence
Section titled “Replace first occurrence”echo “hello world” | sed “s/world/universe/“
Output: hello universe
Section titled “Output: hello universe”Replace all occurrences (g flag)
Section titled “Replace all occurrences (g flag)”cat file.txt | sed “s/old/new/g”
Replace in file
Section titled “Replace in file”cat config.txt | sed “s/localhost/192.168.1.1/g”
Practical Examples
Section titled “Practical Examples”Fix common typos
Section titled “Fix common typos”cat document.txt | sed “s/teh/the/g”
Update error status
Section titled “Update error status”cat log.txt | sed “s/ERROR/FIXED/“
Replace multiple spaces with single space
Section titled “Replace multiple spaces with single space”cat data.txt | sed “s/ */ /g”
Remove leading/trailing spaces (simplified)
Section titled “Remove leading/trailing spaces (simplified)”cat file.txt | sed “s/^ *//” # Leading cat file.txt | sed “s/ *$//” # Trailing
Change domain in URLs
Section titled “Change domain in URLs”cat links.txt | sed “s/oldsite.com/newsite.com/g”
Redact passwords
Section titled “Redact passwords”cat config.txt | sed “s/password=.*/password=REDACTED/g”
Combined with Other Commands
Section titled “Combined with Other Commands”Find and replace, then save
Section titled “Find and replace, then save”cat config.txt | sed “s/debug=true/debug=false/” > new_config.txt
Replace in filtered results
Section titled “Replace in filtered results”cat log.txt | grep “user” | sed “s/username/user_id/g”
Pattern Processing (awk)
Section titled “Pattern Processing (awk)”Extract and process fields from structured text.
Field Extraction
Section titled “Field Extraction”Print first field (default delimiter: space)
Section titled “Print first field (default delimiter: space)”echo “one two three” | awk ‘{print $1}‘
Output: one
Section titled “Output: one”Print second field
Section titled “Print second field”echo “one two three” | awk ‘{print $2}‘
Output: two
Section titled “Output: two”Print last field ($NF = Number of Fields)
Section titled “Print last field ($NF = Number of Fields)”echo “one two three” | awk ‘{print $NF}‘
Output: three
Section titled “Output: three”Print entire line ($0)
Section titled “Print entire line ($0)”echo “hello world” | awk ‘{print $0}‘
Output: hello world
Section titled “Output: hello world”Custom Delimiters
Section titled “Custom Delimiters”Use colon as delimiter
Section titled “Use colon as delimiter”cat /etc/passwd | awk -F: ‘{print $1}‘
Prints usernames (first field)
Section titled “Prints usernames (first field)”CSV processing
Section titled “CSV processing”cat data.csv | awk -F, ‘{print $1}‘
Print first column
Section titled “Print first column”Custom delimiter with -F flag
Section titled “Custom delimiter with -F flag”echo “a:b:c:d” | awk -F: ‘{print $2}‘
Output: b
Section titled “Output: b”Tab-delimited
Section titled “Tab-delimited”cat data.tsv | awk -F”\t” ‘{print $1 $3}‘
Multiple Fields
Section titled “Multiple Fields”Print multiple fields
Section titled “Print multiple fields”cat /etc/passwd | awk -F: ‘{print $1 $3}‘
Print username and UID
Section titled “Print username and UID”Fields with custom separator
Section titled “Fields with custom separator”echo “a b c d” | awk ‘{print $1, $3}‘
Output: a c
Section titled “Output: a c”Combine fields
Section titled “Combine fields”cat data.csv | awk -F, ‘{print $1 ”-” $2}‘
Field Count
Section titled “Field Count”Print number of fields
Section titled “Print number of fields”echo “one two three four” | awk ‘{print NF}‘
Output: 4
Section titled “Output: 4”Use NF to get last field
Section titled “Use NF to get last field”echo “a b c d e” | awk ‘{print $NF}‘
Output: e
Section titled “Output: e”Practical Examples
Section titled “Practical Examples”Extract usernames from passwd
Section titled “Extract usernames from passwd”cat /etc/passwd | awk -F: ‘{print $1}‘
Get IP addresses from netstat-like output
Section titled “Get IP addresses from netstat-like output”netstat | awk ‘{print $5}’ | awk -F: ‘{print $1}‘
Extract file names from ls -l
Section titled “Extract file names from ls -l”ls -l | awk ‘{print $9}‘
Process CSV: extract name and email
Section titled “Process CSV: extract name and email”cat users.csv | awk -F, ‘{print $1 $3}‘
Get second column from space-separated data
Section titled “Get second column from space-separated data”cat data.txt | awk ‘{print $2}‘
Print first and last fields
Section titled “Print first and last fields”echo “start middle1 middle2 end” | awk ‘{print $1 $NF}‘
Output: start end
Section titled “Output: start end”Sorting and Deduplication
Section titled “Sorting and Deduplication”Sort Command
Section titled “Sort Command”Alphabetical sort
Section titled “Alphabetical sort”cat names.txt | sort
Reverse alphabetical sort
Section titled “Reverse alphabetical sort”cat names.txt | sort -r
Numeric sort
Section titled “Numeric sort”cat numbers.txt | sort -n
Example input: 10, 2, 100
Section titled “Example input: 10, 2, 100”Alphabetical: 10, 100, 2
Section titled “Alphabetical: 10, 100, 2”Numeric (-n): 2, 10, 100
Section titled “Numeric (-n): 2, 10, 100”Numeric reverse sort
Section titled “Numeric reverse sort”cat scores.txt | sort -rn
Unique Command
Section titled “Unique Command”Remove consecutive duplicates
Section titled “Remove consecutive duplicates”cat file.txt | uniq
Count occurrences
Section titled “Count occurrences”cat file.txt | uniq -c
Case-insensitive deduplication
Section titled “Case-insensitive deduplication”cat file.txt | uniq -i
Combined Sort and Unique
Section titled “Combined Sort and Unique”Sort and remove duplicates
Section titled “Sort and remove duplicates”cat names.txt | sort | uniq
Sort, deduplicate, and count
Section titled “Sort, deduplicate, and count”cat log.txt | sort | uniq -c
Numeric sort with deduplication
Section titled “Numeric sort with deduplication”cat numbers.txt | sort -n | uniq
Find most common entries
Section titled “Find most common entries”cat access.log | sort | uniq -c | sort -rn
Practical Examples
Section titled “Practical Examples”Sort usernames
Section titled “Sort usernames”cat /etc/passwd | awk -F: ‘{print $1}’ | sort
List unique IPs from log
Section titled “List unique IPs from log”cat access.log | awk ‘{print $1}’ | sort | uniq
Top 10 most common errors
Section titled “Top 10 most common errors”cat error.log | grep “ERROR” | sort | uniq -c | sort -rn | head -10
Alphabetize and deduplicate list
Section titled “Alphabetize and deduplicate list”cat email_list.txt | sort | uniq > clean_list.txt
String Manipulation
Section titled “String Manipulation”Reverse (rev)
Section titled “Reverse (rev)”Reverse a string
Section titled “Reverse a string”echo “hello” | rev
Output: olleh
Section titled “Output: olleh”Reverse each line
Section titled “Reverse each line”echo “hello world” | rev
Output: dlrow olleh
Section titled “Output: dlrow olleh”Reverse file contents line by line
Section titled “Reverse file contents line by line”cat file.txt | rev
Split Command
Section titled “Split Command”Split by space (default)
Section titled “Split by space (default)”echo “one two three” | split
Output: [one, two, three]
Section titled “Output: [one, two, three]”Split by custom delimiter
Section titled “Split by custom delimiter”echo “a,b,c,d” | split ,
Output: [a, b, c, d]
Section titled “Output: [a, b, c, d]”Split by colon
Section titled “Split by colon”echo “name:email:phone” | split :
Output: [name, email, phone]
Section titled “Output: [name, email, phone]”Split CSV
Section titled “Split CSV”echo “red,green,blue” | split ,
Output: [red, green, blue]
Section titled “Output: [red, green, blue]”Join Command
Section titled “Join Command”Join with space (default)
Section titled “Join with space (default)”echo [“hello”, “world”] | join
Output: hello world
Section titled “Output: hello world”Join with custom delimiter
Section titled “Join with custom delimiter”echo [“a”, “b”, “c”] | join -
Output: a-b-c
Section titled “Output: a-b-c”Join with comma
Section titled “Join with comma”echo [“red”, “green”, “blue”] | join ,
Output: red,green,blue
Section titled “Output: red,green,blue”Join with empty string
Section titled “Join with empty string”echo [“h”, “e”, “l”, “l”, “o”] | join ""
Output: hello
Section titled “Output: hello”Trim Command
Section titled “Trim Command”Remove leading and trailing whitespace
Section titled “Remove leading and trailing whitespace”echo ” hello ” | trim
Output: hello
Section titled “Output: hello”Trim multiple lines
Section titled “Trim multiple lines”cat file.txt | trim
Trim in pipeline
Section titled “Trim in pipeline”cat data.txt | grep “value” | trim
Practical Examples
Section titled “Practical Examples”Split CSV and process
Section titled “Split CSV and process”cat data.csv | split , | awk ‘{print $1}‘
Reverse and rejoin
Section titled “Reverse and rejoin”echo “hello world” | split | rev | join ” “
Clean and join list
Section titled “Clean and join list”cat items.txt | trim | sort | join ”, “
File Operations
Section titled “File Operations”Cat Command
Section titled “Cat Command”Display file contents
Section titled “Display file contents”cat /etc/passwd | wc -l
Cat with pipe
Section titled “Cat with pipe”cat file.txt | grep “error”
Multiple operations
Section titled “Multiple operations”cat log.txt | grep “warning” | wc -l
Ls Command
Section titled “Ls Command”List current directory
Section titled “List current directory”ls
List specific directory
Section titled “List specific directory”ls /home ls /etc
Long format (-l): shows permissions, size, filename
Section titled “Long format (-l): shows permissions, size, filename”ls -l ls -l /var/log
Show all files (-a): includes hidden files starting with .
Section titled “Show all files (-a): includes hidden files starting with .”ls -a ls -a /home/user
Human-readable sizes (-h): displays sizes as K, M, G
Section titled “Human-readable sizes (-h): displays sizes as K, M, G”ls -lh ls -lh /var/log
Combined flags
Section titled “Combined flags”ls -la # Long format with all files ls -lah # Long format, all files, human-readable ls -lh /var # Long format with human sizes
List and filter with grep
Section titled “List and filter with grep”ls | grep “.txt” ls /etc | grep “conf” ls -l | grep “log”
List and count
Section titled “List and count”ls | wc -l ls /var/log | grep “.log” | wc -l
List and sort
Section titled “List and sort”ls | sort ls -l | sort
List to file (redirection)
Section titled “List to file (redirection)”ls > filelist.txt ls -la >> directory_contents.txt
Find Command
Section titled “Find Command”Find files by name
Section titled “Find files by name”find /home -name “*.txt” | wc -l
Find and process
Section titled “Find and process”find . -type f | grep “.log”
Find and count
Section titled “Find and count”find /var/log -name “*.log” | wc -l
Find specific files
Section titled “Find specific files”find . -name “config.conf” | wc -l
Echo Command
Section titled “Echo Command”Print text
Section titled “Print text”echo “hello world” | wc -w
Echo and process
Section titled “Echo and process”echo “test string” | grep “test”
Echo to file (redirection, not pipe)
Section titled “Echo to file (redirection, not pipe)”echo “log entry” >> log.txt
Echo list
Section titled “Echo list”echo [“a”, “b”, “c”] | join ,
Nslookup Command
Section titled “Nslookup Command”Lookup hostname
Section titled “Lookup hostname”echo “example.com” | nslookup
Returns IP address
Section titled “Returns IP address”Process list of hostnames
Section titled “Process list of hostnames”cat domains.txt | nslookup
Lookup and save results
Section titled “Lookup and save results”echo “google.com” | nslookup > ip.txt
Process Listing (ps)
Section titled “Process Listing (ps)”List running processes on the computer in a format suitable for pipe processing.
Basic Usage
Section titled “Basic Usage”List all processes
Section titled “List all processes”ps
Output format: USER PID CPU% MEM% COMMAND
Section titled “Output format: USER PID CPU% MEM% COMMAND”Example: root 1234 5.2% 12.3% /bin/sshd
Section titled “Example: root 1234 5.2% 12.3% /bin/sshd”Filter by User
Section titled “Filter by User”Show only root’s processes
Section titled “Show only root’s processes”ps -u root
Show specific user’s processes
Section titled “Show specific user’s processes”ps -u guest
Count root’s processes
Section titled “Count root’s processes”ps -u root | wc -l
Filter by Command
Section titled “Filter by Command”Show processes with “sshd” in command name
Section titled “Show processes with “sshd” in command name”ps -C sshd
Show all bash processes
Section titled “Show all bash processes”ps -C bash
Show Python processes
Section titled “Show Python processes”ps -C python
Combined Filters
Section titled “Combined Filters”Show root’s bash processes
Section titled “Show root’s bash processes”ps -u root -C bash
Show guest’s Python processes
Section titled “Show guest’s Python processes”ps -u guest -C python | wc -l
Process Analysis with Pipes
Section titled “Process Analysis with Pipes”Count total running processes
Section titled “Count total running processes”ps | wc -l
Find specific process
Section titled “Find specific process”ps | grep “nginx”
List all process commands
Section titled “List all process commands”ps | awk ‘{print $5}‘
Show non-root processes
Section titled “Show non-root processes”ps | grep -v “root”
Extract PIDs only
Section titled “Extract PIDs only”ps | awk ‘{print $2}‘
Show processes sorted by user
Section titled “Show processes sorted by user”ps | sort
Count processes by command type
Section titled “Count processes by command type”ps | awk ‘{print $5}’ | sort | uniq -c
Common Use Cases
Section titled “Common Use Cases”Monitor specific service
Section titled “Monitor specific service”ps -C apache2 | wc -l
Check if process is running
Section titled “Check if process is running”ps | grep “mysql”
List all user processes
Section titled “List all user processes”ps | grep -v “root” | wc -l
Get process statistics
Section titled “Get process statistics”ps -u root | wc -l ps -u guest | wc -l
Export process list
Section titled “Export process list”ps > processes.txt
Filter and save
Section titled “Filter and save”ps -u root > root_processes.txt
Word Counting (wc)
Section titled “Word Counting (wc)”Line Count
Section titled “Line Count”Count lines
Section titled “Count lines”cat file.txt | wc -l
Count matching lines
Section titled “Count matching lines”cat log.txt | grep “error” | wc -l
Count files
Section titled “Count files”ls | wc -l
Count users
Section titled “Count users”cat /etc/passwd | wc -l
Word Count
Section titled “Word Count”Count words
Section titled “Count words”cat file.txt | wc -w
Count words in string
Section titled “Count words in string”echo “hello world test” | wc -w
Output: 3
Section titled “Output: 3”Count words after filtering
Section titled “Count words after filtering”cat document.txt | grep “chapter” | wc -w
Character Count
Section titled “Character Count”Count characters
Section titled “Count characters”cat file.txt | wc -c
Count characters in string
Section titled “Count characters in string”echo “hello” | wc -c
Output: 5
Section titled “Output: 5”Count filtered characters
Section titled “Count filtered characters”cat file.txt | grep “error” | wc -c
Practical Examples
Section titled “Practical Examples”Count error occurrences
Section titled “Count error occurrences”cat system.log | grep -i “error” | wc -l
Count unique users
Section titled “Count unique users”cat access.log | awk ‘{print $1}’ | sort | uniq | wc -l
Total word count in all files
Section titled “Total word count in all files”cat *.txt | wc -w
Count non-comment lines
Section titled “Count non-comment lines”cat script.src | grep -v ”^//” | wc -l
Field Extraction (cut)
Section titled “Field Extraction (cut)”Column Extraction
Section titled “Column Extraction”Extract first column (default delimiter: tab)
Section titled “Extract first column (default delimiter: tab)”cat data.txt | cut -f1
Extract column from CSV
Section titled “Extract column from CSV”cat data.csv | cut -d, -f1
Extract multiple columns
Section titled “Extract multiple columns”cat data.csv | cut -d, -f1,3
Extract range of columns
Section titled “Extract range of columns”cat data.csv | cut -d, -f2-4
Character Extraction
Section titled “Character Extraction”Extract first 10 characters
Section titled “Extract first 10 characters”cat file.txt | cut -c1-10
Extract characters 5 to 15
Section titled “Extract characters 5 to 15”cat file.txt | cut -c5-15
Extract from position to end
Section titled “Extract from position to end”cat file.txt | cut -c10-
Practical Examples
Section titled “Practical Examples”Extract usernames (first field, colon delimiter)
Section titled “Extract usernames (first field, colon delimiter)”cat /etc/passwd | cut -d: -f1
Extract IP addresses (first field, space delimiter)
Section titled “Extract IP addresses (first field, space delimiter)”cat access.log | cut -d” ” -f1
Extract date from log
Section titled “Extract date from log”cat log.txt | cut -c1-10
Extract email domain
Section titled “Extract email domain”cat emails.txt | cut -d@ -f2
Get filename from path
Section titled “Get filename from path”echo “/home/user/file.txt” | cut -d/ -f4
Character Translation (tr)
Section titled “Character Translation (tr)”Character Replacement
Section titled “Character Replacement”Replace characters
Section titled “Replace characters”echo “hello” | tr “e” “a”
Output: hallo
Section titled “Output: hallo”Multiple character replacement
Section titled “Multiple character replacement”echo “hello” | tr “el” “ax”
Output: haxxo
Section titled “Output: haxxo”Replace spaces with underscores
Section titled “Replace spaces with underscores”echo “hello world” | tr ” ” ”_“
Output: hello_world
Section titled “Output: hello_world”Case Conversion
Section titled “Case Conversion”Lowercase to uppercase
Section titled “Lowercase to uppercase”echo “hello” | tr “a-z” “A-Z”
Output: HELLO
Section titled “Output: HELLO”Uppercase to lowercase
Section titled “Uppercase to lowercase”echo “HELLO” | tr “A-Z” “a-z”
Output: hello
Section titled “Output: hello”Mixed case
Section titled “Mixed case”echo “Hello World” | tr “A-Z” “a-z”
Output: hello world
Section titled “Output: hello world”Practical Examples
Section titled “Practical Examples”Convert DOS to Unix line endings
Section titled “Convert DOS to Unix line endings”cat dosfile.txt | tr -d “\r”
Remove all numbers
Section titled “Remove all numbers”cat file.txt | tr -d “0-9”
Replace all vowels
Section titled “Replace all vowels”echo “hello world” | tr “aeiou” ”*****“
Output: hll w*rld
Section titled “Output: hll w*rld”Clean up filenames (spaces to underscores)
Section titled “Clean up filenames (spaces to underscores)”echo “my file name.txt” | tr ” ” ”_“
Output: my_file_name.txt
Section titled “Output: my_file_name.txt”Head and Tail
Section titled “Head and Tail”Display first or last N lines/bytes from input.
Head Command
Section titled “Head Command”Display first N lines
Section titled “Display first N lines”cat file.txt | head -n 5
Show first 5 lines
Section titled “Show first 5 lines”echo [“line1”, “line2”, “line3”, “line4”, “line5”] | head -n 3
Output: [“line1”, “line2”, “line3”]
Section titled “Output: [“line1”, “line2”, “line3”]”Display first N bytes
Section titled “Display first N bytes”cat file.txt | head -c 100
Show first 100 bytes
Section titled “Show first 100 bytes”Default shows first 10 lines
Section titled “Default shows first 10 lines”cat log.txt | head
Show first 10 lines
Section titled “Show first 10 lines”Tail Command
Section titled “Tail Command”Display last N lines
Section titled “Display last N lines”cat file.txt | tail -n 5
Show last 5 lines
Section titled “Show last 5 lines”echo [“line1”, “line2”, “line3”, “line4”, “line5”] | tail -n 2
Output: [“line4”, “line5”]
Section titled “Output: [“line4”, “line5”]”Skip first N lines with +NUM syntax
Section titled “Skip first N lines with +NUM syntax”cat data.csv | tail -n +2
Show from line 2 onwards (skip header)
Section titled “Show from line 2 onwards (skip header)”Display last N bytes
Section titled “Display last N bytes”cat file.txt | tail -c 100
Show last 100 bytes
Section titled “Show last 100 bytes”Show from byte N to end with +NUM syntax
Section titled “Show from byte N to end with +NUM syntax”cat file.txt | tail -c +50
Show from byte 50 to end
Section titled “Show from byte 50 to end”Default shows last 10 lines
Section titled “Default shows last 10 lines”cat log.txt | tail
Show last 10 lines
Section titled “Show last 10 lines”Practical Examples
Section titled “Practical Examples”Remove CSV header
Section titled “Remove CSV header”cat data.csv | tail -n +2 | head -n 10
Skip first line, show next 10
Section titled “Skip first line, show next 10”Process list without header
Section titled “Process list without header”ps | tail -n +2 | sort
Remove ps header, sort remaining
Section titled “Remove ps header, sort remaining”Get middle section
Section titled “Get middle section”cat file.txt | head -n 50 | tail -n 10
Lines 41-50
Section titled “Lines 41-50”Extract specific byte range
Section titled “Extract specific byte range”cat binary.dat | tail -c +100 | head -c 50
Bytes 100-149
Section titled “Bytes 100-149”Sample first entries from each section
Section titled “Sample first entries from each section”cat log.txt | grep “ERROR” | head -n 5
First 5 errors
Section titled “First 5 errors”Show last few entries
Section titled “Show last few entries”cat access.log | grep “404” | tail -n 10
Last 10 404 errors
Section titled “Last 10 404 errors”Complex Pipeline Examples
Section titled “Complex Pipeline Examples”Log Analysis
Section titled “Log Analysis”Find unique error IPs and count them
Section titled “Find unique error IPs and count them”cat access.log | grep “error” | awk ‘{print $1}’ | sort | uniq -c | sort -rn
Extract failed login attempts
Section titled “Extract failed login attempts”cat auth.log | grep “Failed password” | awk ‘{print $11}’ | sort | uniq -c
Top 10 most accessed pages
Section titled “Top 10 most accessed pages”cat access.log | awk ‘{print $7}’ | sort | uniq -c | sort -rn | head -n 10
Recent errors from large log (skip old entries)
Section titled “Recent errors from large log (skip old entries)”cat huge.log | tail -n 10000 | grep “ERROR” | tail -n 50
Process data without headers
Section titled “Process data without headers”cat report.csv | tail -n +2 | awk -F, ‘{print $1}’ | sort | uniq
Data Processing
Section titled “Data Processing”Extract and clean email list
Section titled “Extract and clean email list”cat contacts.txt | grep ”@” | cut -d, -f2 | trim | sort | uniq
Calculate average from numbers
Section titled “Calculate average from numbers”cat numbers.txt | awk ‘{sum+=$1} END {print sum/NR}‘
Filter, extract, and count
Section titled “Filter, extract, and count”cat data.csv | grep -v ”^#” | cut -d, -f3 | sort -n | uniq -c
File Management
Section titled “File Management”Find large log files
Section titled “Find large log files”find /var/log -name “*.log” | xargs ls -lh | grep “M”
Count source files excluding tests
Section titled “Count source files excluding tests”find . -name “*.src” | grep -v test | wc -l
List duplicate filenames
Section titled “List duplicate filenames”find . -type f | awk -F/ ‘{print $NF}’ | sort | uniq -d
Text Processing
Section titled “Text Processing”Extract emails and domains
Section titled “Extract emails and domains”cat file.txt | grep -o “[a-z]@[a-z].[a-z]*” | cut -d@ -f2 | sort | uniq
Clean and format list
Section titled “Clean and format list”cat raw_list.txt | trim | sort | uniq | awk ‘{print ”- ” $0}‘
Process multi-column data
Section titled “Process multi-column data”cat data.txt | awk ‘{print $1 ”,” $3}’ | sort | sed “s/,/ -> /g”
Combined Operations
Section titled “Combined Operations”Extract, filter, transform, and count
Section titled “Extract, filter, transform, and count”cat /etc/passwd | cut -d: -f1 | grep -v ”^#” | sort | wc -l
Multi-stage text transformation
Section titled “Multi-stage text transformation”cat input.txt | tr “A-Z” “a-z” | sed “s/old/new/g” | sort | uniq
Complex log analysis
Section titled “Complex log analysis”cat access.log | grep “POST” | awk ‘{print $1}’ | sort | uniq -c | sort -rn | head -20
Data validation pipeline
Section titled “Data validation pipeline”cat data.csv | grep -v ”^$” | cut -d, -f1-3 | trim | sort | uniq > clean_data.csv
Output Redirection
Section titled “Output Redirection”Write to File
Section titled “Write to File”Overwrite file
Section titled “Overwrite file”cat input.txt | grep “error” > errors.txt
Append to file (cat still uses pipe internally)
Section titled “Append to file (cat still uses pipe internally)”cat new_log.txt | cat >> main_log.txt
Save processed results
Section titled “Save processed results”cat data.txt | sort | uniq > unique_data.txt
Clipboard Operations
Section titled “Clipboard Operations”Copy to clipboard
Section titled “Copy to clipboard”cat file.txt | xclip
Copy filtered results
Section titled “Copy filtered results”cat log.txt | grep “error” | xclip
Copy processed data
Section titled “Copy processed data”cat list.txt | sort | uniq | xclip
Tips and Best Practices
Section titled “Tips and Best Practices”- Start Simple: Build pipes incrementally, testing each stage
- Use grep -v: Exclude unwanted lines before processing
- Sort Before uniq:
uniqonly removes consecutive duplicates - Check Field Numbers: Use
awk '{print NF}'to count fields - Test Regex: Verify patterns with simple grep before complex pipes
- Use -n for Numbers: Sort numeric data with
sort -n - Trim Data: Use
trimto clean whitespace before processing - Redirect Output: Save results with
>or>> - Count Results: End pipes with
wc -lto count matches - Debug Pipes: Remove stages from end to isolate issues
Common Patterns
Section titled “Common Patterns”Filter, extract, deduplicate
Section titled “Filter, extract, deduplicate”cat file.txt | grep “pattern” | awk ‘{print $2}’ | sort | uniq
Count unique values
Section titled “Count unique values”cat data.txt | awk ‘{print $1}’ | sort | uniq | wc -l
Top N most common
Section titled “Top N most common”cat file.txt | sort | uniq -c | sort -rn | head -10
Clean and save
Section titled “Clean and save”cat raw.txt | trim | sort | uniq > clean.txt
Multi-field extraction
Section titled “Multi-field extraction”cat data.csv | cut -d, -f1,3 | sort
Case-insensitive deduplication
Section titled “Case-insensitive deduplication”cat list.txt | tr “A-Z” “a-z” | sort | uniq
Error Handling
Section titled “Error Handling”- Empty results return
[] - Invalid commands return Error objects
- File not found returns
[] - Permission denied returns
[] - Invalid regex patterns fail silently
Performance Considerations
Section titled “Performance Considerations”- Large files: Use grep to filter early in pipeline
- Memory usage: Avoid loading entire files when possible
- Sorting: Can be expensive on large datasets
- Regex: Complex patterns slow down grep
- Field extraction: awk is efficient for structured data