Substring extraction using bash shell scripting and awk

17,592

Solution 1

You would need to put the closing backtick after the end of the awk command, but it's preferable to use $() instead:

result=$( grep 'packet loss' dummy |
awk '{  first=match($0,"[0-9]+%")
    last=match($0," packet loss")
    s=substr($0,first,last-first)
    print s}' )

echo $result

but you could just do:

result=$( grep 'packet loss' | grep -o "[0-9]\+%" )

Solution 2

Try

awk '{print $3}'

instead.

Solution 3

the solution below can be used when you don't know where the percentage numbers are( and there's no need to use awk with greps)

$ results=$(awk '/packet loss/{for(i=1;i<=NF;i++)if($i~/[0-9]+%$/)print $i}' file)
$ echo $results
100%

Solution 4

You could do this with bash alone using expr.

i=`expr "There is 98.76% packet loss at node 1" : '[^0-9.]*\([0-9.]*%\)[^0-9.]*'`; echo $i;

This extracts the substring matching the regex within \( \).

Share:
17,592
GobiasKoffi
Author by

GobiasKoffi

Updated on June 05, 2022

Comments

  • GobiasKoffi
    GobiasKoffi almost 2 years

    So, I have a file called 'dummy' which contains the string:

    "There is 100% packet loss at node 1".
    

    I also have a small script that I want to use to grab the percentage from this file. The script is below.

    result=`grep 'packet loss' dummy` |
    awk '{  first=match($0,"[0-9]+%")
            last=match($0," packet loss")
            s=substr($0,first,last-first)
            print s}'
    
    echo $result
    

    I want the value of $result to basically be 100% in this case. But for some reason, it just prints out a blank string. Can anyone help me?