Practical Pipe Patterns
As mentioned before, longer multi-pipe commands are built iteratively – one command at a time. However, there are some useful patterns that you’ll see re-used frequently.
“Top X”, with count
This pattern sorts the input by number of occurrences, descending. You saw this in the original example from this chapter, which displayed the most frequently used shell commands from Bash’s history file.
Here’s the pattern:
some_input | sort | uniq -c | sort -rn | head -n 3
- The input is sorted alphabetically, and then run through
uniq -c
, which needs sorted input to work on. uniq -c
eliminates duplicates, but adds a count (-c
) of how many duplicates it found for each entry.sort
is run again, this time as a reverse-numeric (-r
and-n
) sort which sorts the unique counts from the input and outputs the lines in reverse (highest number first) sorted order.head
takes that top ranking and cuts it down to three lines (-n 3
), giving you...