shBash

Bash: Text processing – code examples

Contents

Analyze Error Frequency in a Log

Text processing#awk#log#count#uniq
Use case: Quickly check how many messages per level (INFO/WARN/ERROR) a log file contains.
awk '{ zaehler[$3]++ } END { for (l in zaehler) print l, zaehler[l] }' server.log | sort
# Example output:
# ERROR 2
# INFO 3
# WARN 1

awk 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

Text processing#tr#sort#uniq#pipe
Use case: Text analysis, e.g. finding the most-used terms in a file.
tr -cs '[:alpha:]' '\n' < datei.txt \
  | tr '[:upper:]' '[:lower:]' \
  | sort | uniq -c | sort -rn | head -n 10

tr -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

Text processing#awk#csv#sum
Use case: Sum, filter or reformat table values without Excel.
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

Text processing#sed#replace#find
Use case: Swap configuration values or domains across many 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"
done

sed -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

Text processing#log#awk#uniq#top
Use case: Find suspicious requests (bots, attacks) in a web server 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 | head

A classic log pipeline: extract a column, sort, count (uniq -c needs sorted input!), sort by frequency, take the top 5.