Which topic appears most often in a list? In Episode 4 of Liko Learns Linux, we’ll answer that question using four simple terminal examples. Along the way, you’ll learn how to count lines, sort text, and use a pipe to connect two commands.
Set up the practice file
Use a text editor to save these six lines as topics.txt,
with one topic per line. Press Enter after the last line before saving.
Then open a terminal in the folder containing the file.
Linux
Python
Linux
Bash
Python
Linux
1. Count the lines with wc -l
wc -l topics.txt
The -l option uses a lowercase letter L. It counts newline
characters, so this file gives a count of six, including the repeated topics.
6 topics.txt
2. Put the topics in order with sort
sort topics.txt
This prints the lines in alphabetical order. Notice how the repeated entries are now next to each other.
Bash Linux Linux Linux Python Python
3. Show each topic once with uniq
sort topics.txt | uniq
The pipe symbol | passes the output of sort
to uniq. Since uniq only combines identical lines
that are next to each other, sorting first puts all copies of each topic
together.
Bash Linux Python
4. Count each topic with uniq -c
sort topics.txt | uniq -c
The -c option prints the count before each topic.
Linux appears three times, making it the most frequent topic in the list.
1 Bash
3 Linux
2 Python
Try it yourself
Add two more lines containing Python to
topics.txt. Run wc -l topics.txt and
sort topics.txt | uniq -c again. What is the new total,
and which topic appears most often now?
No comments:
Post a Comment