extract key values

I am parsing a log with key values spread all over in the following fashion:

TEST 1 SCHEME 12 SET EMPTY
VARLEN SET TEST 1201 PARAM1 EMTY PARAM2 SET
SCHEME 12 REFRESH TEST 8

I need to extract test number, my result should be

1
1201
8

I use awk for processing this log and use split to search for the values:

n = split($0, a);
for(i = 1; i <= n; i++) {
        if(a == "TEST") {
                value = a[i+1]; 
        }       
}       

I suspect my code is not efficient, I thought of using index($0, "TEST") within substr etc.., but my code ended up using two index() calls and this is not the best way either.

Any ideas how to improve the code would be appreciated.

grep & regex

grep -o 'TEST [0-9]*' file | cut -d' ' -f2

If your grep doesn't support -o option:

sed -n '/TEST [0-9][0-9]*/ s/.*TEST \([0-9][0-9]*\).*/\1/p' file

Anchal

The command is good .
can u explain the command?

'/TEST [0-9][0-9]*/

searching for the pattern. TEST<space><one or more digits>

s/.*TEST \([0-9][0-9]*\).*/\1/p'

removing everything but the required numbers from the above matched lines.

\(..\) are used to save the regex/pattern found.
\1 are used to recall the above regex/pattern.

you can have max 9 such recalls.

1 Like