Bash: Text processing – code examples
Analyze Error Frequency in a Log
awk '{ zaehler[$3]++ } END { for (l in zaehler) print l, zaehler[l] }' server.log | sort
# Example output:
# ERROR 2
# INFO 3
# WARN 1awk counts per value of the 3rd column in an associative array. The output is sorted because awk returns the keys in arbitrary order. Without awk: cut -d" " -f3 server.log | sort | uniq -c.
Count the Most Frequent Words
tr -cs '[:alpha:]' '\n' < datei.txt \
| tr '[:upper:]' '[:lower:]' \
| sort | uniq -c | sort -rn | head -n 10tr -cs splits into words (non-letters become newlines), sort | uniq -c counts, sort -rn sorts descending. A classic pipe chain. Umlauts in tr depend on locale and system (GNU/Linux with UTF-8 works, BSD/macOS sometimes does not).
Analyze CSV with awk
cat > daten.csv <<'EOF'
name,stadt,alter
Ada,Berlin,36
Ben,Hamburg,25
Cem,Berlin,41
EOF
awk -F, 'NR > 1 { summe += $3; n++ } END { print "Average age:", summe / n }' daten.csv
awk -F, 'NR > 1 && $2 == "Berlin" { print $1 }' daten.csv-F, sets the delimiter, NR > 1 skips the header line. Result: average age 34 and the names Ada, Cem. For CSV with quotes and commas inside fields, awk is unsuitable – use csvkit or Python there.
Replace Text in Files
# Portable (GNU and BSD/macOS): via a temporary file
sed 's/localhost/db.example.com/g' config.ini > config.ini.neu && mv config.ini.neu config.ini
# Several files with find + loop
find . -name "*.conf" -print0 | while IFS= read -r -d '' f; do
sed 's/alt/neu/g' "$f" > "$f.tmp" && mv "$f.tmp" "$f"
donesed -i behaves differently on GNU (-i) and macOS (-i ''). The variant via a temp file runs everywhere. -print0 and read -d '' are safe with spaces in file names.
Top IPs from an Access Log
# Assumption: the first column is the IP address (Apache/Nginx combined format)
awk '{ print $1 }' access.log | sort | uniq -c | sort -rn | head -n 5
# or only error accesses (status in column 9)
awk '$9 >= 500 { print $1 }' access.log | sort | uniq -c | sort -rn | headA classic log pipeline: extract a column, sort, count (uniq -c needs sorted input!), sort by frequency, take the top 5.