AkshaiShah
AkshaiShah

Reputation: 5939

Extract grep match with sed

I'm trying to run the following:

echo $line | grep "u01/app/[0-9]" | sed -n 's/[0-9]|\./p'

Where

line="orb 14171 orb 3u REG 253,3 0 14141 /u01/app/11.2.0.4/broa/log/stm1025/agent/"

And what I would like to do is extract the version number, and store it in a variable, but whenever I run the above command, all I seem to get it sed: command garbled: s/[0-9]p

Anyone know what's wrong?

Upvotes: 1

Views: 152

Answers (3)

zmo
zmo

Reputation: 24802

when I run your sed command, my sed is telling:

sed -n 's/[0-9]|\./p'
sed: 1: "s/[0-9]|\./p": unterminated substitute in regular expression

which is because you did not make a full substitution command, the substitution command has the following syntax : s/…/…/ whereas you only made it s/…/.

you can try, to stick with sed:

echo $line | sed -e 's,.*/u01/app/\([0-9\.]*\)*/.*,\1,'
11.2.0.4

Upvotes: 2

Jotne
Jotne

Reputation: 41460

You can try awk

ver=$(awk -F/ '/u01\/app\/[0-9]/ {print $4}' <<< "$line")
echo "$ver"
11.2.0.4

It takes the fourth field from the variable line and store it to a variable ver

If its only one line in the variable, you can skip the test and use:

ver=$(awk -F/ '{print $4}' <<< "$line")

Simple to understand, and just give the value directly. No complicated regex :)

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 247202

Assuming you have bash and GNU grep:

version=$(grep -oP '(?<=/u01/app/).+?(?=/)' <<< "$line")
echo "$version"    # => 11.2.0.4

That PCRE regex finds all characters between /u01/app/ and the next /

Upvotes: 2

Related Questions