I'm trying to learn command line better and wondering what the difference between these two commands would be.

grep -c ^b example  


grep ^b example| cat –n
  • 2
    Welcome to Unix & Linux. If you want to learn the command line, the best way is to experiment by running the commands yourself using different input files. Questions should show some research effort so I'd advise checking the relevant man pages to find out the purpose of the different options. Man pages aren't the most readable if you're new to Unix, so if you have any issues understanding it, you could edit this question to make it more specific (and useful). See How to Ask and feel free to take the tour. – Anthony Geoghegan Jan 12 '18 at 21:35
  • (-1) Not even the same commands. Two unrelated commands. – Isaac Jan 12 '18 at 22:04
  • Did you try running the commands? – Sparhawk Jan 13 '18 at 2:12

Well, according to the manual, grep:

searches for PATTERN in each FILE. By default, grep prints the matching lines.

and with the -c flag:

-c, --count

Suppress normal output; instead print a count of matching lines for each input file.

So, grep -c ^b example prints the number (count) of lines matching the pattern, while grep ^b example prints the lines themselves.

As for cat, it's described to

concatenate files and print on the standard output

and what the -n flag does is to:

-n, --number    

number all output lines

Given the pipe and no file names, cat reads from the pipe, so the output is the output of grep, with line numbers added. Hence grep ^b example| cat –n prints all matching lines, numbered.

This is different from grep -n ^b example, where grep adds the line numbers of the matches. grep knows the line numbers of the original file, while cat only sees the output of grep and numbers the lines accordingly.

So, given the input file

$ cat example 

We have:

$ grep -c ^b example 

$ grep ^b example |cat -n
     1  bar
     2  basf

$ grep -n ^b example

Ok command:

  1. grep -c ^b example: Output the count for matching lines for lines that begin with letter b, and

  2. grep ^b example | cat -n: pass the result of the grep command to the cat command and list them with line numbers. The -n forces cat to list them along with lines numbers.


example.txt with content:

media sound3
media sound1
media sound2
find sound -type f -name sound[0-9] -printf 'media %f\n' > file.txt
find sound -type f -name sound[0-9] -exec bash -c 'echo media bash >> file.txt' {} \;
find sound -type f -name sound[0-9] -exec bash -c "f='{}'; echo media $( basename ${f}) >> file.txt" \;

Result from (1):


Result from (2):

1   media sound3
2   media sound1
3   media sound2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.