Search

Liko Save Terminal Output Episode 5 : Echo , Tee

In Episode 4 of Liko Learns Linux, we counted how often each topic appeared in a list. In Episode 5, we’ll turn those counts into a report and save it from the terminal.

Set up the practice file

Use topics.txt from Episode 4, or save these six lines in a new file with that name. Open a terminal in the folder containing the file.

Linux
Python
Linux
Bash
Python
Linux

1. Print a heading with echo

echo "Topic report"

echo prints Topic report on the next line in the terminal.

2. Write the heading to a file with >

echo "Topic report" > topic_report.txt

The shell sends the output to topic_report.txt, so the heading no longer appears on screen. A single > creates the file if needed and replaces its contents if it already exists. Use a fresh filename for practice.

3. Append the counts with >>

sort topics.txt | uniq -c >> topic_report.txt
cat topic_report.txt

sort groups identical topics, and uniq -c counts them. The double >> adds those counts below the heading. Use cat to check the finished report.

Topic report
      1 Bash
      3 Linux
      2 Python

4. Display and save the counts with tee

sort topics.txt | uniq -c | tee topic_counts.txt

tee shows the counts in the terminal and writes the same output to topic_counts.txt. By default, it replaces the file’s contents if the file already exists.

Try it yourself

Append a final line to your report, then read it again to check that the heading and counts are still there.

echo "End of report" >> topic_report.txt
cat topic_report.txt

No comments:

Post a Comment