I’ve created a file called fruits consisting of strawberry, kiwi, and banana. I wanted to find strawberry using the |
pipe.
cat fruits | grep strawberry
While learning, I understand that not all commands support |
, and we need to use cat -
. How do we use this command?
I’ve tried cat - | grep strawberry
or cat - fruits | grep strawberry
. Both runs but never stop.
Advertisement
Answer
When you specify a file name of -
, cat
reads standard input (your terminal). It’s a common convention; many other commands use -
to indicate ‘read standard input’. You have to tell cat
that you’ve reached EOF by typing Control-D on Unix-like systems, or Control-Z on Windows systems.
You have:
cat - | grep strawberry
— this will run until you indicate EOF.cat - fruits | grep strawberry
— this too runs until you indicate EOF, but then processes the filefruits
too.
You say “not all commands support |
“. That is barely true. The shell implements the |
operator. If a program is a pure generator (for example, ls
or ps
), then it will ignore standard input, so piping data to ls
or ps
is pointless. But piping the output of the commands makes sense.
You also mention using:
cat fruits | grep strawberry
That certainly works, but it is unnecessary — you could use
grep strawberry fruits
to avoid the overhead of the extra process and the pipe. This is an example of UUoC — Useless Use of cat
.