如何从批处理脚本中获取 Java 版本? [英] How to get Java Version from batch script?

查看:31
本文介绍了如何从批处理脚本中获取 Java 版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从下面给出的 Java 版本输出中获取 '6'

I am trying to get '6' out of the java version output given below

java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)

同样我写了这个批处理脚本

For the same I wrote this batch script

set VERSION6="1.6.0_21"
java -version 2>&1 | findstr "version" >ab.txt
for /f "tokens=3" %%g in (ab.txt) do (
  if not %%g == %VERSION6% echo %%g
  echo %%g
)

%%g 显示1.6.0_21"

%%g displays "1.6.0_21"

有人可以指导我正确的方向吗?我对 for/f 不太熟悉.

May someone guide me to correct direction? I am not much familiar with for /f.

推荐答案

@echo off
setlocal

set VERSION6="1.6.0_21"
for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do (
    @echo Output: %%g
    set JAVAVER=%%g
)
set JAVAVER=%JAVAVER:"=%
@echo Output: %JAVAVER%

for /f "delims=. tokens=1-3" %%v in ("%JAVAVER%") do (
    @echo Major: %%v
    @echo Minor: %%w
    @echo Build: %%x
)

endlocal

在第一个 for 循环中,"tokens=3" 表示我们将只使用命令输出中的第三个标记.我们可以在 for 循环本身内运行此命令,而不是将 java -version 命令的输出重定向到文件.插入符号 (^) 是转义字符,需要这样我们才能嵌入 >&| 命令字符串中的符号.

In the first for loop, "tokens=3" says that we're going to just use the third token from the command output. Rather than redirect the output of the java -version command to a file, we can run this command within the for loop itself. The carets (^) are escape characters, and are needed so we can embed the >, & and | symbols in the command string.

for 循环的主体内,我们设置了一个新的 var,JAVAVER,以便我们稍后可以对版本字符串进行一些操作.

Within the body of the for loop, we set a new var, JAVAVER, so that we can do some manipulation of the version string later.

set JAVAVER=%JAVAVER:"=% 命令删除版本字符串周围的双引号.

The set JAVAVER=%JAVAVER:"=% command removes the double quotes from around the version string.

最后一个 for 循环解析 java 版本字符串.delims=. 表示我们将使用句点分隔标记.tokens=1-3 表示我们要将字符串中的前三个标记传递给循环体.我们现在可以使用显式变量 %%v 和隐含变量(字母表中的下一个字母)%%w 获取 java 版本字符串的组件>%%x.

The last for loop parses the java version string. delims=. says we're going to delimit tokens using periods. tokens=1-3 says we're going to pass the first three tokens from the string to the body of the loop. We can now get the components of the java version string using the explicit variable, %%v and the implied variables (next letters in the alphabet) %%w and %%x.

当我在我的系统上运行它时,我得到:

When I run this on my system I get:

Output: "1.6.0_24" 
Output: 1.6.0_24
Major: 1 
Minor: 6 
Build: 0_24

这篇关于如何从批处理脚本中获取 Java 版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆