2

I'm writing a simple script to monitoring the disk space in the / partition and I want to grep only numbers in my output.

tabbi@tabbi:~/scripts$ df -h / 
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda2       234G  7,6G  214G   4% /

Let's say I want to remove the % from the Use column (or remove it everywhere); when I use df -h / | grep -v '%' nothing is printed.

How can I exclude the % symbol from my output?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

2 Answers2

4

grep -v removes any line matching the given string; so in your case, any line containing “%” is deleted, in its entirety.

To remove the character only, use tr:

df -h / | tr -d %
Stephen Kitt
  • 434,908
  • Beware the df header line and the Gs, that should be: df -h / | tr -d %G | tail -1 – Rui F Ribeiro Mar 09 '18 at 12:33
  • We don’t know what the OP really wants, do we? I’m basing my answer on “How can I exclude the % symbol from my output?” And to avoid issues with G, M etc. the better approach is to drop the -h option. – Stephen Kitt Mar 09 '18 at 12:35
  • The question could be better worded, for sure. Complain to the people doing moderation for being so lax. – Rui F Ribeiro Mar 09 '18 at 12:36
1

You can get the / directory usage, without "%", with awk. Basically, the awk in following command:

  • Selects the last line of output, to account for the df header - END;
  • deletes "%";
  • outputs the fifth field (print $5).

    df -h / | awk '  END { gsub("%",""); print $5 } '
    

Running it:

$ df -h / | awk '  END { gsub("%",""); print $5 } '
4

Or to get all numbers:

$ df -h / | awk '  END { gsub("%",""); gsub("G",""); print $2" "$3" "$4" "$5 } '
234 7,6 214 4
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
  • @StephenKitt Works well without it...why the -P? df -h is not being affected by -P , only df default output. – Rui F Ribeiro Mar 09 '18 at 12:50
  • @StephenKitt I have never seen two lines in dfand it seems not affecting df -h. Will investigate that, thanks. – Rui F Ribeiro Mar 09 '18 at 13:00
  • @StephenKitt /* Note the SOURCE_FIELD used to be displayed on it's own line if (!posix_format && mbswidth (cell) > 20), but that functionality was probably more problematic than helpful, hence changed in commit v8.10-40-g99679ff. */ – Rui F Ribeiro Mar 09 '18 at 13:06
  • 1
    Wow, nice, it’s only been seven years or so! We need to update a bunch of answers here ;-). – Stephen Kitt Mar 09 '18 at 13:12