To understand the practical use of Grep's option -H in different situations

一笑奈何 提交于 2019-12-03 16:10:24

Grep will list the filenames by default if more than one filename is given. The -H option makes it do that even if only one filename is given. In both your examples, more than one filename is given.

Here's a better example:

$ grep Richie notes.txt
Richie wears glasses.

$ grep -H Richie notes.txt
notes.txt:Richie wears glasses.

It's more useful when you're giving it a wildcard for an unknown number of files, and you always want the filenames printed even if the wildcard only matches one file.

If you grep a single file, -H makes a difference:

$ grep muel mesi
muel

$ grep -H muel mesi
masi:muel

This could be significant in various scripting contexts. For example, a script (or a non-trivial piped series of commands) might not be aware of how many files it's actually dealing with: one, or many.

When you grep from multiple files, by default it shows the name of the file where the match was found. If you specify -H, the file name will always be shown, even if you grep from a single file. You can specify -h to never show the file name.

Emacs has grep interface (M-x grep, M-x lgrep, M-x rgrep). If you ask Emacs to search for foo in the current directory, then Emacs calls grep and process the grep output and then present you with results with clickable links. Clickable links, just like Google.

What Emacs does is that it passes two options to grep: -n (show line number) and -H (show filenames even if only one file. the point is consistency) and then turn the output into clickable links.

In general, consistency is good for being a good API, but consistency conflicts with DWIM.

When you directly use grep, you want DWIM, so you don't pass -H.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!