Keeping header of an output while grepping the rest for something else in BASH

Sometimes it is useful to keep the header of an output of some command while grepping the same output for something else. In the example below, the column information is absent:

The solution is to pipe the STDOUT to head using output duplication of tee via process substitution.

This works in BASH, but other POSIX-compliant SHELLs may not have process substitution implemented. The command tee works as a splitter: the data goes to STDOUT and also its duplicate is written to a file ("file.txt" in the example below):

STDOUT of tee is piped into STDIN of grep and instead of file.txt process substitution >(head -1) is used, where temporary file descriptors are created. Although head -1 is an another process, it's STDIN is mapped to STDIN of a temporary file and >(head -1) is treated as a file descriptor.

There is a more POSIX-friendly solution based on pee command from moreutils package:

The pee program pipes the the output of "ps aux" to multiple commands which are listed in pee's input arguments. Note that their execution is done in parallel, so to ensure the desired order of execution you can add a pause between the commands:

Also you can use grepping capabilities of sed:


Another alternative is awk. Print the line if it contains "systemd" or if the number of rows is equal to 1: