How to GREP a substring in a string that is a destination variable?

I have an output that has the format

OK: CpuUser = 0.11; CpuNice = 0.00; CpuSystem = 0.12; CpuIowait = 0.02; CpuSteal = 0.00;

I only want to get the output of CpuIowait = 0.12. I want to grep only a specific substring. How to do it?

+3


source to share


4 answers


You can use a flag -o

(only). This command:

grep -o 'CpuIowait=[^;]*'

      



will print out the specific substrings that match CpuIowait=[^;]*

, instead of printing out all the lines that contain them.

+7


source


If you want to use grep

, try something like this:



echo "OK: CpuUser=0.11; CpuNice=0.00; CpuSystem=0.12; CpuIowait=0.02; CpuSteal=0.00;" | grep -oE "CpuIowait=[[:digit:]]*\.[[:digit:]]*"

      

+3


source


If you are not in the mood to use grep, you can pipe the input to sed:

sed -ne "s / ^. (CpuSystem = [0-9.]); * $ / \ 1 / p;"

+1


source


To get the whole line:

var=$(grep -Eo 'CpuIowait=[0-9]{1,2}[.][0-9]{2}' < <(command))

      

To only get the value if you have GNU grep with -P you can use the following:

var=$(grep -Po '(?<=CpuIowait=).*(?=;)' < <(command))

      

Using awk:

var=$(awk -F'; |: ' '{ for (i=0;i<=NF;i++) { split($i,arr,/=/); if (arr[1] ==  "CpuIowait") { print arr[2] } } }' < <(command))

      

Using pure bash:

output=$(command)
[[ $output =~ (CpuIowait=[0-9][.][0-9]{2}) ]] && echo "${BASH_REMATCH[1]}"

      

+1


source







All Articles