Answering to the third question: of course it can be used meaningfully in the way at Bash manual clearly hints – in a trap, e. g.:
$ trap 'echo ‘$BASH_COMMAND’ failed with error code $?' ERR
$ fgfdjsa
fgfdjsa: command not found
‘fgfdjsa’ failed with error code 127
$ cat /etc/fgfdjsa
cat: /etc/fgfdjsa: No such file or directory
‘cat /etc/fgfdjsa’ failed with error code 1
You can use grep
with PCRE (-P
):
grep -Po 'spring.profiles.active=\K[^ ]+' <<<'.....string.....'
spring.profiles.active=
will match this substring literally, \K
will discard the match
[^ ]+
will select the desired portion i.e. the portion after spring.profiles.active=
, till the next space
For a file:
grep -Po 'spring.profiles.active=\K[^ ]+' file.txt
Example:
% grep -Po 'spring.profiles.active=\K[^ ]+' <<<'00:28:04 /usr/lib/jvm/jre/bin/java -DJDBC_CONNECTION_STRING= -Dspring.profiles.active=qa -XX:MaxPermSize=256'
qa
sed
would take similar logic:
sed -r 's/.*spring.profiles.active=([^ ]+).*/\1/' <<<'.....string.....'
Example:
% sed -r 's/.*spring.profiles.active=([^ ]+).*/\1/' <<<'00:28:04 /usr/lib/jvm/jre/bin/java -DJDBC_CONNECTION_STRING= -Dspring.profiles.active=qa -XX:MaxPermSize=256'
qa
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 above sed
example, you obtain the whole original string, which could create problems:
% var="$(sed -r 's/.*spring.profiles.active=([^ ]+).*/\1/' <<<'00:28:04 /usr/lib/jvm/jre/bin/java -DJDBC_CONNECTION_STRING= -XX:MaxPermSize=256')"
% echo $var
00:28:04 /usr/lib/jvm/jre/bin/java -DJDBC_CONNECTION_STRING= -XX:MaxPermSize=256
If you prefer to obtain the empty string when there is no match, add the -n
option to the sed
command and the p
option to the sed
s
command, like this:
% var="$(sed -rn 's/.*spring.profiles.active=([^ ]+).*/\1/p' <<<'00:28:04 /usr/lib/jvm/jre/bin/java -DJDBC_CONNECTION_STRING= -XX:MaxPermSize=256')"
% echo $var
% var="$(sed -rn 's/.*spring.profiles.active=([^ ]+).*/\1/p' <<<'00:28:04 /usr/lib/jvm/jre/bin/java -DJDBC_CONNECTION_STRING= -Dspring.profiles.active=qa -XX:MaxPermSize=256')"
% echo $var
qa
Then you can test if $var is empty or not.
Best Answer
-P
enables PEARL like behaviour (which enables you to use the+
), and the-o
tells grep to only output the matching part of the string. Each match will be printed to a new linehead -2
.