How can I store the first line of output to print as a header after matching all lines that start with /dev/nvme?

Right now I'm calling df twice, but I would like to do it in one pass with awk.

df -h | grep '^Filesystem' && df -h | grep '^/dev/nvme'

Desired results would be:

Filesystem      Size  Used Avail Use% Mounted on
/dev/nvme0n1p2  ...
/dev/nvme0n1p1 ...
  • 2
    df -h | awk 'NR==1 || /^\/dev\/nvme*/' – jasonwryan Apr 24 '17 at 2:33
  • 1
    df != du, for the record. But why not provide the paths you're checking to df directly: df -h /dev/nvme* – DopeGhoti Apr 24 '17 at 2:35
  • 2
    ... except you don't need/want the * (it's not a glob) – steeldriver Apr 24 '17 at 2:35
  • @jasonwryan the statement NR==1 || /^\/dev\/nvme*/ is tested against every line correct? (if total number of records =1 or line starts with /dev/nvme) – jes516 Apr 24 '17 at 2:59
  • Yes, awk reads every line of input, unless instructed otherwise. It's default action is to print, so it prints the first line and any that match the pattern. – jasonwryan Apr 24 '17 at 3:03

As noted by others:

df -Ph | awk 'NR == 1 || $0 ~ "^/dev/nvme"'

Alternatively, Linux df allows you to specify the device file on the command line:

df -x devtmpfs -Ph /dev/nvme*

The -x devtmpfs is to prevent the /dev filesystem from showing up when a matching device is not mounted.

The -P option guarantees that df won't break a line even if one of the columns is wide.

The advantage with the second method is that df will space the columns appropriately for the output.

  • I tried df -h /dev/nvme* and as you mentioned, it showed 2 /dev filesystem entries. – jes516 Apr 24 '17 at 3:29
  • @jes516 - You missed the -x devtmpfs part – DarkHeart Apr 24 '17 at 3:30
  • Works perfect with -x devtmpfs – jes516 Apr 24 '17 at 3:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.