Include header in the ‘grep’ result

The following means you only need type the command once (rather than using && and typing it twice), it’s also quite simple to understand.

some-command | { head -1; grep some-stuff; }

e.g.

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

UPDATE: This only seems to work for ps, sorry, but I guess this is usually what people want this for.

If you want this to work for an arbitrary command, it seems you must write a mini script, e.g.:

#!/bin/bash

first_line=true

while read -r line; do
    if [ "${first_line}" = "true" ]; then
        echo "$line"
        first_line=false
    fi
    echo "$line" | grep $*
done

Which I’ve named hgrep.sh. Then you can use like this:

ps -ef | ./hgrep.sh -i chrome

The nice thing about this approach is that we are using grep so all the flags work exactly the same.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)