Want to highlight if certain condition match with full output in linux

42 Views Asked by At

I want to highlight the Use% column if it reaches above 80. Any color is fine but I want it with full output.

Filesystem             Size  Used Avail Use% Mounted on
devtmpfs               6.3G     0  6.3G   0% /dev
tmpfs                  6.3G  4.0K  6.3G   1% /dev/shm
tmpfs                  6.3G  1.1G  5.2G  18% /run
tmpfs                  6.3G     0  6.3G   0% /sys/fs/cgroup
/dev/mapper/os-root    9.5G  7.1G  2.0G  79% /
/dev/mapper/os-var      60G   37G   21G  65% /var
/dev/mapper/os-varlog   15G   11G  3.4G  77% /var/log
/dev/vda3              197M  173M   25M  88% /boot
tmpfs                  1.3G     0  1.3G   0% /run/user/0

For example, in my case,

Filesystem             Size  Used Avail Use% Mounted on
devtmpfs               6.3G     0  6.3G   0% /dev
tmpfs                  6.3G  4.0K  6.3G   1% /dev/shm
tmpfs                  6.3G  1.1G  5.2G  18% /run
tmpfs                  6.3G     0  6.3G   0% /sys/fs/cgroup
/dev/mapper/os-root    9.5G  7.1G  2.0G  79% /
/dev/mapper/os-var      60G   37G   21G  65% /var
/dev/mapper/os-varlog   15G   11G  3.4G  77% /var/log
**/dev/vda3              197M  173M   25M  88% /boot** -->* 88% color should change here.*
tmpfs                  1.3G     0  1.3G   0% /run/user/0

is it possible? or not? please help me guys. Sorry for my bad English.

1

There are 1 best solutions below

4
Gilles Quénot On BEST ANSWER

You can do it like this:

with :

df -h |
    perl -anE '
        (my $p = $F[4]) =~ s/%//;
        if ($p >= 80) {
            system("tput setaf 1");
            print;
            system("tput sgr0")
        }
        else {
            print
        }
    '

Or with just :

df -h | 
    while read line; do
        if [[ $line =~ (100|[8-9][0-9])% ]]; then
            tput setaf 1
            echo "$line"
            tput sgr0
        else
            echo "$line"
        fi
    done

Or even with :

df -h |
    awk '
        NR==1{print;next}
        {
            p=$5
            p=gensub(/%/, "", 1, $5)
            if (p>=80) {
                system("tput setaf 1")
                print
                system("tput sgr0")
            }
            else print
        }
    '

The basic idea is to use terminfo database to not hardcode terminal escape sequences.

I use tput with the sequence names from man terminfo to get the right code in terminal.

Eg.

red=$(tput setaf 1); echo "Hello ${red}world!"

more info at http://www.gnu.org/software/termutils/