0

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.

Koala
  • 29
  • 4

3 Answers3

3

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 file fruits 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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1

If cat - doesn't stop it's because the symbol "-" is for parameter. And you run cat with no parameter. Actually, it didn't run indefinitely; the shell waits for you to enter the end of the command.

cat is a command that simply reads files.

In your example, it will read your file fruits. And the pipe | means the output of cat will be the input of your grep.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Hpn4
  • 119
  • 6
0

You're supposed to use some options after cat -

Suppose if you use cat -n file_name it will show you the content of the file by giving it the line number

iamdhavalparmar
  • 1,090
  • 6
  • 23
  • 1
    The dash on its own has a specific meaning, unrelated to options like `-n`. You can even repeat it: `cat - -` is legitimate if unorthodox (and decidedly different from `cat --`). – Jonathan Leffler Mar 10 '21 at 12:47