← Back to Home

Linux Text Manipulation Cheat Sheet

Master text processing in Linux using essential commands like grep, sed, awk, cut, tr, and more.

1. grep - Search Text in Files

Find lines containing “error”

grep "error" logs.txt

Case-insensitive search

grep -i "warning" syslog.txt

Exclude matching lines

grep -v "DEBUG" logs.txt

2. sed - Stream Editor

Replace “Linux” with “Ubuntu”

sed 's/Linux/Ubuntu/' file.txt

Delete lines containing “error”

sed '/error/d' file.txt

Modify text inline

sed -i 's/old/new/g' file.txt

3. awk - Process Structured Text

Print second column

awk '{print $2}' data.txt

Filter rows where column 3 > 100

awk '$3 > 100 {print $1, $3}' data.txt

Use a custom delimiter (CSV)

awk -F, '{print $2}' data.csv

4. cut - Extract Text Columns

Extract characters 1-5

cut -c1-5 file.txt

Extract second column (default delimiter: tab)

cut -f2 data.txt

Extract third column from CSV

cut -d',' -f3 data.csv

5. tr - Translate or Delete Characters

Convert lowercase to uppercase

echo "hello world" | tr 'a-z' 'A-Z'

Remove digits

echo "abc123" | tr -d '0-9'

Replace spaces with underscores

echo "hello world" | tr ' ' '_'

6. sort - Sort Data

Sort alphabetically

sort names.txt

Sort numerically

sort -n numbers.txt

Sort in reverse order

sort -r names.txt

7. uniq - Remove Duplicate Lines

Remove consecutive duplicates

uniq sorted.txt

Count occurrences

uniq -c sorted.txt

8. paste - Merge Lines

Combine two files column-wise

paste file1.txt file2.txt

Use a custom delimiter (comma)

paste -d',' file1.txt file2.txt

9. tee - Output & Save to File

Display and save output

ls -l | tee output.txt

Append output to a file

ls -l | tee -a output.txt

10. wc - Count Lines, Words, Characters

Count lines

wc -l file.txt

Count words

wc -w file.txt

Count characters

wc -c file.txt

11. head & tail - View File Sections

Show first 10 lines

head file.txt

Show last 10 lines

tail file.txt

Monitor logs in real-time

tail -f /var/log/syslog

12. nl - Add Line Numbers

Number all lines

nl file.txt

13. rev - Reverse Text

Reverse each line

echo "hello" | rev

14. fold - Wrap Long Lines

Wrap text at 40 characters

fold -w 40 file.txt

15. column - Format Text into Columns

Format data into a table

column -t data.txt

Specify a custom delimiter (colon)

column -t -s ":" data.txt

Practical Example Log Analysis

Extract unique IPs from a log file, sort, and count occurrences

awk '{print $1}' access.log | sort | uniq -c | sort -nr