Sikau

Linux and the shell · Day 9 · about 35 min

sed and awk

Find-and-replace with sed; columns and sums with awk.

Edit without an editor

sed (stream editor) rewrites text line by line — perfect for changing a config value on 50 servers. awk treats each line as columns and is a tiny programming language for reports.

sed and awk in practice

sed 's/momo/dumpling/gi' menu.csv | head -3
sed -n '2,4p' menu.csv
sed '/^name/d' menu.csv | head -2
sed -i 's/port=3000/port=8080/' app.conf
cat app.conf
awk -F, '{ print $1 }' menu.csv | head -3
awk -F, 'NR > 1 && $3 > 150 { print $1, $3 }' menu.csv
awk -F, 'NR > 1 { total += $3 } END { print "avg", total / (NR - 1) }' menu.csv
awk -F, 'NR > 1 { n[$2]++ } END { for (c in n) print c, n[c] }' menu.csv

The rest of this lesson

  • sed safely in placeexplain
  • awk for quick reportsexplain
  • What prints?predict
  • sed or awk?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 16 lessons of Linux and the shell