I have a string
00:28:04 /usr/lib/jvm/jre/bin/java -DJDBC_CONNECTION_STRING= -Dspring.profiles.active=qa -XX:MaxPermSize=256
and want to extract the word qa
that follows -Dspring.profiles.active
.
I have the string save in a file text.txt just to demo on it.
When I do
grep -r -o "spring.profiles.active=" text.txt
The result is spring.profiles.active=
This word does not always be qa
, it could be prod
or dev
.
What I'd like to do is find the word spring.profiles.active
and after the =
extract that word.
I would like to shell script this because I use the word to configure other items on the server.
Is this possible and if so, how do I do it.
Best Answer
You can use
grep
with PCRE (-P
):spring.profiles.active=
will match this substring literally,\K
will discard the match[^ ]+
will select the desired portion i.e. the portion afterspring.profiles.active=
, till the next spaceFor a file:
Example:
sed
would take similar logic:Example:
Handling errors:
In your script you may want to handle the case where there is no match, in other words where your original string does not contain
spring.profiles.active=
. In the abovesed
example, you obtain the whole original string, which could create problems:If you prefer to obtain the empty string when there is no match, add the
-n
option to thesed
command and thep
option to thesed
s
command, like this:Then you can test if $var is empty or not.