1

When I enter ls command I get the below output.

-$ ls
aNode  ANode  bNode  BNode  cNode  CNode  DUMP  file1  hello.txt  TEST.txt
-$

As seen, above output is one line which has filenames separeted by spaces.

Next when I use grep to find a match.

I was expecting that if a match is found then the entire line will be printed.

But, on the contrary, grep only prints the match but not the entire line containing the match. Please see below.

-$ ls | grep 'aNode'
aNode
-$

Why is this happening ? Why is grep not printing the entire line ?

marked as duplicate by cuonglm, Mikel, G-Man, Ramesh, Anthon Jun 11 '15 at 3:46

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

6

ls has different output formats and displays things differently if it's writing to a terminal instead of a pipe. When writing to a pipe it writes just one entry per line, so grep can work on each listing individually.

So when you do that grep you are getting a different output from ls than when you just run ls and print to the screen.

You can see the same affect that grep is experiencing if you do

ls | cat

which will display all the entries, one per line.

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