Wednesday, December 29, 2021

[SOLVED] How to extract specific data from grep command in bash?

Issue

I'm trying to write my own script to tell me if I've used more than 500 MiB of my data. I'm using vnstat -d for the information about data usage. vnstat -d Output here enter image description here

Output should be:

  1. Only from the "Total column"
  2. Only have values greater than 500.

I want only values from the "total"column. My output lists data from all the columns. Better clear from the following:

#!/bin/bash
for i in `vnstat -d | grep -a [0-9] `; //get numerical values in i (-a tag as vnstat outputs in binary)
do 
    NUMBER=$(echo $i | grep -o '[5-9][0-9][0-9]'); //store values >500 in a var called NUMBER
    echo $NUMBER;
done;

I'm a self-learning newb here so please try not to bash (pun) me.

Current output which I'm receiving from above script:

600
654
925
884
923
871
967
868

My desired output should be:

654   
923    
967

Solution

Simplified:

#/bin/bash
if [[ $(( $(vnstat -d --oneline|cut -d';' -f6|cut -d. -f1|paste -sd '+') )) -ge 500 ]];then
  echo 500 Mb reached
fi

(What the script does, is it takes the specified field from the oneliner CSV-like output from each interface, then cuts the whole numbers and does a SUM of them. And then it compares if that sum is equal or greater than 500. And if it is, then it outputs a message)

Note:

-f6 will parse the "total for today" traffic

you can replace it with:

-f4 = rx for today

-f5 = tx for today



Answered By - Ron