0
votes

I was interested in keeping the header of the input in the grep output just like in the question Include header in the 'grep' result.

Although a working solution (using sed) is presented right in the question, the answer with most upvotes attracted my attention. It allows utilizing grep --color, for example. It suggests piping the input to a command group with the commands head and grep, e.g.:

ps -ef | { head -1; grep python; }

However, as written in the linked answer and a comment, this does not work with all commands on the left side of the pipe. It works well with ps or lsof but does not work for df, ls and others. When using them, only the output of the first command in the group is printed:

$ df | { head -1; grep '/'; }
Filesystem                                   1K-blocks      Used Available Use% Mounted on
$

Could anyone explain why piping to a command group only works for some commands? Is there any way to make it work universally?

1
In general I think you shouldn't rely on the second command receiving any input. - Tom Fenech
You can use awk to print first line or matching lines... ps -ef | awk 'NR==1 || /python/' - Mark Setchell

1 Answers

1
votes

The answer to your question is in comments of the linked answer.

Apparently ps -e is sending the header line first, then not sending anything, then buffering the rest of the output. head must think the stream is closed after the first line, so it exits, leaving grep to see the rest.

It only works by accident.

Is there any way to make it work universally?

Everything is possible, but, you may need to recode and recompile everything else. So... not possible, sorry.