Thanks to dteske for the idea

df -h | while read line; do [ -n “$var” ] || echo $line; var=1; echo $line | grep p8; done

NOTE: how you can do several things with each line (like you can with awk), using a while read VARIABLE loop (format while read line; do STUFF; done;). (VARIABLE here for us is line)

Output:

Normal Output:

So what happens in that command?

Red text is your typical grep statement df -h | grep p8 everything in between is what prints the first (header) line & whichever line greps “p8”

Normal output:

 

Here is what happens. df -h is piped to a while read line loop. Basically every line of the df -h output will be set to the variable $line. We determine the variable line in the read statement (we could of used other word, like i). The first time the loop evaluates, the line variable will be set to the first line of the output of df -h (the header).┬áThe way I got it to only print the first line is by checking for a set variable $var. The first time its run, var wont be set (unless something is using the $var variable in your system; in which case you can change the var to something else or surround the entire command with parenthesis and run it again so that it runs in a subshell and doesnt interfere), so that [ -n “$var” ] will evaluate as false and that echo $line will print that line (which is the first line). Immediately after that we set the variable to some trivial value (var=1, I could of set it to var=”grampa” if I wanted to). After that we echo the line thru our grep statement which will only print it, if grep finds the contents.

Leave a Reply

Your email address will not be published. Required fields are marked *