Home > database >  Get substring of regex from string
Get substring of regex from string

Time:08-18

I am using a bash script to parse logs and need to extract a substring.

My string is something like this -

TestingmkJHSBD,MFV from testing:2.6.1.566-978.7 testing 

How can I extract this string using bash

CodePudding user response:

Would you please try the following:

awk '
    /FROM image/ {
        if (match($0, /image[^[:space:]] /))
            print(substr($0, RSTART, RLENGTH))
    }
' logfile
  • The regex image[^[:space:]] matches a substring which starts with image and followed by non-space character(s).
  • Then the awk variables RSTART and RLENGTH are assigned to the position and the length of the matched substring.

CodePudding user response:

Another awk option:

awk '{if ($0 ~ /FROM image/) {for (i=1; i<=NF; i  ) if ($i ~ /^image/) {print $i} }}' <<<"TestingmkJHSBD,MFV FROM image/something/docker:2.6.1.566-978.7 testing"

Output:

image/something/docker:2.6.1.566-978.7

Or using different log string:

awk '{if ($0 ~ /FROM image/) {for (i=1; i<=NF; i  ) if ($i ~ /^image/) {print $i} }}' <<<"bdkjf asfjkklsdfsg FROM image/something/docker:2.6.1.566-978.7 testing"

Output:

image/something/docker:2.6.1.566-978.7
  • Related