Unix Pipes

A pipe bridges two processes together. The pipe, written with the | character, connects the output of one command to the input of the second. It’s one of the fundamental building blocks of a Unix shell.

A very basic example is using cat to feed the contents of a file to the word count tool wc:

$ cat <filename> | wc

Just in case you didn’t know these commands:

  • cat prints the contents of a file.
  • wc counts all the lines, words and bytes it is fed.

Another often-used version is wc -l, which only counts the number of lines in a file.

Let’s try this. First, create a file called words.txt with this content:

hello
world
python
ninja
are
you
?
3
2
1

Then run this command:

$ cat words.txt | wc -l

The output should be 10 since there are 10 lines in the file. Another example is using sort to sort the words in your file:

$ cat words.txt | sort
?
are
hello
ninja
python
world
you
1
2
3

As we can see, all the words from words.txt are fed to sort, which sorts them. Punctuation first, then numbers and then letters.

Alright. Here’s one last, questionable example of using pipes. There’s this awesome tool called cowsay. It generates an ASCII picture of a cow saying something that you feed it:

$ echo "Are we going to learn anything useful?" | cowsay
 ________________________________________
< Are we going to learn anything useful? >
 ----------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

This is the stuff that will make a lasting impression on your colleagues.

Get Certified and advance your career

Our premium courses offer a superior user experience with small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

The Python Fundamentals Course For Beginners

Python Fundamentals I is a course for beginners that will get you started with Python in no time. Learn all the essentials, test your progress with quizzes and assignments, and bring it together with the final course project!

The Python Course for Beginners

Modules, Packages, And Virtual Environments

Python Fundamentals II covers creating modules and packages, using virtual environments and Python package managers to make your life as a programmer easier. Advance your productivity as a Python programmer!

If this article helped you, please help us out and share it!

Leave a Comment

I hope you’re enjoying my articles. Perhaps you’d like to sign up for my weekly newsletter as well. You’ll receive:

Super easy to unsubscribe & Your data stays on Python Land.

Footer subscribe

No, thanks!

Share to...