Why doesn't grep return the whole line in this

2019-09-01 12:04发布

This question already has an answer here:

I am practicing using the terminal in Mac OSX.

I went to the /dev/ folder from root, and wanted to look for the line containing null, so I did ls to get the folder contents. There was a lot, so I saw this as an opportunity to use grep. So I typed ls | grep "null" and simply got back null instead of the full line null ttyp9 as shown in the normal ls listing.

Why is this happening? I thought grep returned full lines?

2条回答
混吃等死
2楼-- · 2019-09-01 12:18

ttyp9 is a different file.

ls is showing you columns of output.

When not sent to the terminal ls doesn't do that and acts as if you used the -1 argument.

查看更多
Bombasti
3楼-- · 2019-09-01 12:39

grep does return full lines. The ls command by itself does not give details. Try this instead:

ls -l | grep "null"

That listing flag gives more details, which grep can then return.

In other words, grep was doing what you wanted it to, there was just nothing there to see.

The ls command without options will just show filenames. Typically the returned list of filenames is wrapped. You can unwrap them if you type:

ls -1

If you look at this listing, you will see that null is actually on a line all by itself.

If you add the long listing option:

ls -l

You will see much more detail. The grep command can only return what is given to it, and the in this case ls is what is supplying all the inputs for grep.

查看更多
登录 后发表回答