1

I have a directory with some files -

mkdir _tmpmm
touch a1 b2 c3 d4
ls
# a1  b2  c3  d4

When I grep for a on the output of ls, I see only the file a1 - although the ls output is showing 4 files on the same line

ls | grep a
# a1

However, if I create a file named "file_with_names.txt" containing the following lines -

cat file_with_names.txt
# a1 b2 c3 d4
# xxx
# zaz

And then do either

grep a file_with_names.txt

OR

cat file_with_names.txt | grep a

I get -

# a1 b2 c3 d4
# zaz

So, my question is - why does grepping for a on the ls output not return the full line - i.e. a1 b2 c3 d4?

Mortz
  • 113
  • 4

1 Answers1

2

The grep command matches against the input it's given

Here, the input is the output from ls (bad practice, but let's ignore that for now), so the match is the single file name containing a:

ls | grep a

Here, the input is the output of cat, which in turn is the contents of the file file_with_names.txt:

cat file_with_names.txt | grep a

If you're asking why grep didn't match what you saw as the output from ls, which included four file names, that's because ls produces different output depending on whether it's writing to a terminal for a person to see it writing to a pipe for a subsequent program to see. Try this to see what gets output when it's writing to a pipe:

ls | cat

Generally, it's better not to try and parse the output from ls; there are usually better ways of getting a list of filenames

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
  • 1
    So, the single line output I see when I just do ls is because it has been optimized to display in the terminal while from the perspective of the grep that comes after a | - the output from ls contains newlines? Are there other commands with this kind of behaviour? I mean, different when output to a terminal vs a file? – Mortz Nov 22 '21 at 12:29
  • 1
    Not very many. Some utilities such as rm and mv won't bother asking if you're sure about performing a dubious operation unless there's a terminal from which to receive an answer. The shell will act differently depending on how it's invoked – Chris Davies Nov 22 '21 at 12:32