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.

Please share this article with others!

Python Courses

Are you enjoying this free tutorial? Please also have a look at my premium courses. They offer a superior user experience with small, easy-to-digest lessons and topics, 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
Now for $49 (from $59)

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 all together with the final course project!

Python Course for Beginners

Modules, Packages, And Virtual Environments
Now for $49 (from $59)

Python Fundamentals II covers creating your own 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!

Python Fundamentals 2

Leave a Comment

Share to...