Warm tip: This article is reproduced from serverfault.com, please click

Could not extract jdk-version using grep-command and regular expressions

发布于 2020-11-29 13:33:13

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 ?

Questioner
user14729562
Viewed
0
markp-fuso 2020-11-30 00:52:58

A few small changes to OPs current code:

  • as mentioned in the comments, ^ and $ represent the beginning and ending of the input; remove these from the regex
  • while grep can use the resulting regex it will be necessary to tell grep to run in -Extended regex mode
  • we can use grep's -o option to limit output to just the portion that matches the regex

Sample 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)