I am trying to extract the version of a jdk
using regular-expressions
Actually I have the following version:
openjdk 11.0.9.1 2020-11-04
OpenJDK Runtime Environment (build 11.0.9.1+1-Ubuntu-0ubuntu1.18.04)
OpenJDK 64-Bit Server VM (build 11.0.9.1+1-Ubuntu-0ubuntu1.18.04, mixed mode,sharing)
I wrote the regex. It looks like the following:
^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}$
This regular expression is working on the online regex tester (https://regex101.com/). Unfortunately, it is not working with grep-command. I am using the extended regular expression. My Code for the extraction of jdk-version look like the following:
CMD_RESULT=$(java --version 2>&1 | head -n 1 | cut -d '' -f 2)
if [ ! -z "$CMD_RESULT" ]
then
for token in $CMD_RESULT
do
JAVA_VERSION=$(echo $token | grep -e $VERSION_EXTRACTION_REGEX)
if [ ! -z $JAVA_VERSION ];
then
printf "${GREEN}Java version: [$JAVA_VERSION]\n"
fi
done
fi
I am not understanding, why my regex is working on the online regex checker, while it is not working with the grep-command. I am using the Parameter -e for extended regexp.
Any Idea ?
A few small changes to OPs current code:
^
and $
represent the beginning and ending of the input; remove these from the regexgrep
can use the resulting regex it will be necessary to tell grep
to run in -E
xtended regex modegrep's
-o
option to limit output to just the portion that matches the regexSample input data:
$ cat jdk.dat
openjdk 11.0.9.1 2020-11-04
OpenJDK Runtime Environment (build 11.0.9.1+1-Ubuntu-0ubuntu1.18.04)
OpenJDK 64-Bit Server VM (build 11.0.9.1+1-Ubuntu-0ubuntu1.18.04, mixed mode,sharing)
One grep
solution using OP's modified regex:
$ grep -oE '[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}' jdk.dat
11.0.9.1
11.0.9.1
11.0.9.1
Same thing but with the regex stored in OPs variable:
$ VERSION_EXTRACTION_REGEX='[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}'
$ grep -oE "${VERSION_EXTRACTION_REGEX}" jdk.dat
11.0.9.1
11.0.9.1
11.0.9.1
NOTE: I'll leave it up to the user to decide which value to use, eg, head -n 1
to work with just the first input line (openjdk 11.0.9.1 2020-11-04
)
Uh, I think you mean the opposite; Awk can handle (roughly) ERE syntax, while plain
grep
can't, and requires-E
to enable support.more like ... arg ... was jumping between a couple different answers; have updated to replace the
awk
references withgrep
; and thanks for the edit (perhaps I should step away from the keyboard for a while ...)