0

I am trying to write a cmd script to parse the java version from the java -fullversion command. I am able to retrieve the version like that: 1.6.0_45, 1.7.0_60, 1.8.0_212, 11.0.4. I would like to return the versions as 6, 7, 11. As you can see not all of these appear before the first dot.

I have found the following sed command that works and would like to know the windows cmd equivalent:

sed '/^1\./s///'
user2262955
  • 291
  • 2
  • 3
  • 12
  • 3
    Possible duplicate of [Is there any sed like utility for cmd.exe?](https://stackoverflow.com/questions/127318/is-there-any-sed-like-utility-for-cmd-exe) – Martin Oct 24 '19 at 09:30
  • @Martin, but that's not really an answer to this question. This is about trying to do the same as this specific `sed` command in `cmd`, not about finding a different tool that does this. – Joey Oct 25 '19 at 06:33

1 Answers1

1

This has a few parts, some of which aren't really nice to do:

  1. Get Java's output in a variable

    for /f tokens^=2^ delims^=^" %%v in ('java -fullversion 2^>^&1') do set "version=%%v"
    

    This only retains the part between the quotes, in my case 11.0.4+11.

  2. The sed-like part, which is rather easy:

    if "%version:~0,2%"=="1." set version=%version:~2%
    

    Basically just "if the first two characters are 1., cut them off`.

  3. Cut off everything starting with the first .:

    for /f "tokens=1 delims=." %%v in ("%version%") do set version=%%v
    

    This again uses for /f for parsing and tokenizing and only retains the first token.

Generally these days you can probably use PowerShell as well:

"$(java -fullversion 2>&1)" -replace '.*?([\d.]+).*','$1' -replace '^1\.'
#  ^^^^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
#   Invoke Java and          Replace everything but the    sed equivalent
#   capture stderr           version
Joey
  • 344,408
  • 85
  • 689
  • 683