CHAPTER 5 · 8 lessons · 104 exercises

Reshape text

Sort it, drop duplicates, pull out a column, swap one thing for another. The tools that work on a stream of text.

The last chapter taught you how to join things up. This chapter grows what there is to join to.

Nearly every tool on the command line has the same shape: it takes text and gives back text. Which is why joining a tool that sorts to a tool that drops duplicates gets you a summary.

  • sort — put things in order (as numbers, on a column you pick, in reverse)
  • uniq — drop duplicates that are next to each other (which is why sort comes first)
  • cut — pull out a column
  • tr — swap characters, delete them
  • paste and nl — line things up sideways, number the lines
  • sed — swap text, pull lines out
  • awk — calculate on columns
  • diff — show what differs between two files

sed and awk are small programming languages in their own right, each deep enough for a book. This chapter covers only the shapes you use most — swapping for sed, pulling out columns and adding up for awk. That alone covers nine days out of ten.

Note that uniq can only remove lines that are sitting next to each other. Not knowing that leaves you thinking it is broken, so this chapter has you walk into it on purpose.

Lessons in this chapter

Sort it, drop duplicates

  1. 20Sort it (`sort`)Sort lines with sort. As numbers, in reverse, or on a column you choose.Go to the exercises
  2. 21Drop duplicates, count them (`uniq`)Squash repeated lines with uniq, count them with -c, and learn why sort has to come first.Go to the exercises

Pull out, and replace

  1. 22Pull out a column (`cut`)Use cut to take part of a line. How to name the column by its separator, and where it gives up.Go to the exercises
  2. 23Swap characters, delete them (`tr`)Swap characters one for one with tr. Delete with -d, squeeze runs with -s. A tool that only reads stdin.Go to the exercises
  3. 24Line them up side by side, number them (`paste` and `nl`)Join two files sideways with paste. Number the lines with nl and cat -n.Go to the exercises
  4. 25Swap one piece of text for another (`sed`)Swap text with the s command of sed. Choose lines, delete lines. Rewrite the file itself with -i.Go to the exercises
  5. 26Calculate on columns (`awk`)Pull out columns with awk, choose lines by condition, and get totals and averages. The tool that does what cut could not.Go to the exercises
  6. 27Show the difference (`diff`)Show what differs between two files. How to read - and +, and how to use the exit status.Go to the exercises

Next up is “Permissions”. How to read Permission denied, and how to fix it.