Substr with % - extract numbers only

 # cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.5 (Maipo)

I have this script that will monitor filesystems and send me e-amil alerts.

#! /bin/ksh 
DIST_LIST=monitor@...com

WORKDIR=/home/monitor
WARNLEVEL=90

MAIL_SUBJ="filesystems monitor on "$(hostname)

ALERT_ADMIN () { mail -s "${MAIL_SUBJ}"  $DIST_LIST  << EOF
Filesystem $fsname has reached $sz% of its capacity.
EOF
return
}

cd . > $WORKDIR/freespace.lst
exec 8< $WORKDIR/freespace.lst

df -k | grep -v -i Filesystem | grep -v ":" | awk '{print $5}' |  grep -v "%" | grep -v proc > $WORKDIR/freespace.lst

if [ -f $WORKDIR/freespace.lst ]
then
 while read -u8 fsname sz ;
   do
   if [[ $sz -gt $WARNLEVEL ]]
     then  
        ALERT_ADMIN
    fi 
done 
fi

rm $WORKDIR/freespace.lst

However, the ksh gets % as well.

Filesystem                        Size  Used Avail Use% Mounted on
/dev/mapper/vg00-rootlv            10G  1.9G  8.2G  19% /
devtmpfs                          189G     0  189G   0% /dev
tmpfs                             189G   39M  189G   1% /dev/shm
tmpfs                             189G  380M  188G   1% /run
tmpfs                             189G     0  189G   0% /sys/fs/cgroup
/dev/mapper/vg00-usrlv            5.0G  2.4G  2.7G  47% /usr
/dev/mapper/vg00-tmplv            8.0G   41M  8.0G   1% /tmp
/dev/mapper/vg00-homelv           4.0G   45M  4.0G   2% /home
/dev/mapper/vg00-usrlocallv       2.0G  674M  1.4G  34% /usr/local
/dev/mapper/vg00-optlv            8.0G  563M  7.5G   7% /opt
/dev/mapper/vg00-optstagelv        40G   18G   23G  44% /opt/stage
/dev/emcpowerg2                   976M  262M  648M  29% /boot
/dev/emcpowerg1                   200M  9.8M  191M   5% /boot/efi
/dev/mapper/vg00-varlv            4.0G  1.3G  2.8G  31% /var
19%
0%
1%
1%
0%
47%
1%
2%
34%
7%
44%
29%
5%
31%
31%
1%
4%
2%
11%

Please let me know how to grep numbers only..
I have tried substr($5,1,2) substr($1,1,2), but I am misssing something here.

Thank you!

try the cmd tr:
Tried on my mac...

df -k | grep -v -i Filesystem | grep -v ":" | awk '{print $5}'| tr [%] [\12]

I guess you're looking for awk options / opportunities? There are several:

  • just eliminate the last character: print substr ($5, 1, length($5)-1)
  • eliminate the % character from $5 : sub (/%/, "", $5), print $5
  • or use a feature of awk when doing arithmetics: print $5+0

Once you're at it, and you're using awk anyhow, why not do all of it in awk ?

df -k | awk '! /Filesystem|:/ {print $5+0}' 

An example with shell builtins

df -kP |
while read fs x x x sz mntp junk
do
  if [[ $fs == /dev/* ]] || [[ $mntp == /tmp ]]
  then
    sz=${sz%\%}
    if [[ $sz -gt $WARNLEVEL ]]
    then  
      ALERT_ADMIN
    fi
  fi
done