Connect commands

INPUT · Slides

Pour a file in (`<`)

01 / 06

You can wire up the way in too

It has all been ways out so far. Now for the way in (standard input, number 0).

Just turn the arrow round.

wc -l < names.txt

That means "pour names.txt into the way in of wc". The way the arrow points is the way things flow.

~ $ wc -l < names.txt3

02 / 06

How is that different from writing the file name?

wc -l names.txt gives you the same number. So what changes?

~ $ wc -l names.txt3 names.txt~ $ wc -l < names.txt3

The file name does not come out.

Here is why. When you hand over a file name, wc knows which file it opened, so it puts the name alongside. With < it only had something poured in, so wc does not know any name.

When all you want is the number, < is easier to work with, because the name does not get in the way of whatever you do next.

03 / 06

Some tools only have a way in

There are times when < is the only option: when you use a tool that does not take a file name.

The classic one is tr (the tool that swaps characters).

tr a-z A-Z names.txt    # just prints how to use ittr a-z A-Z < names.txt  # works

tr is built to do nothing but take what comes in the way in, change it, and put it out the way out. So if you want it to read a file, < or a pipe is the only road.

There are other tools like it. When you handed over a file name and nothing happened, try < — that is the fix to remember.

04 / 06

It saves you a cat

You may find yourself wanting to write this.

cat names.txt | wc -l

It works, but the cat is not needed, because < wires it up directly.

wc -l < names.txt

One program fewer, so it is faster, and shorter. An unnecessary cat is one of those things that tells an experienced eye "ah, they have just started", so let us fix it here.

Of course, if you are joining two or more as in cat A B | ..., you do need cat. < can only pour one thing in.

05 / 06

The way in and the way out at once

You can write < and > on the same line.

sort < numbers.txt > sorted.txt

"Read from numbers.txt, sort it, write it to sorted.txt." The way in and the way out sit on either side of the command, and the nice thing is that you can see the flow at a glance.

sort numbers.txt > sorted.txt gives the same result, but writing it with < tells the reader that this command only reads and never touches the original file.

~ $ sort < numbers.txt > sorted.txt~ $ cat sorted.txt123

06 / 06

Now have a go

names.txt holds three names in lower case, and numbers.txt holds three numbers.

Here are the new tools in this lesson. Both of them are the plain sort that takes something in the way in and puts it out the way out.

  • tr — swap characters, or delete them
  • rev — turn each line back to front

It is also a first look at the tools the next chapter goes into properly.