java - 如何从 shell 或 windows 命令行以内联方式执行 java jshell 命令

标签 java java-9 jshell

有没有办法在 REPL (jshell) 上执行 java 命令作为内联命令而不启动它?

例如Perl 内联命令

$perl -e 'printf("%06d", 19)'
000019

我必须启动 jshell 才能运行任何命令:

$jshell
|  Welcome to JShell -- Version 9
|  For an introduction type: /help intro
jshell> String.format("%06d", 19)
$1 ==> "000019"

我发现类似的问题here ,但为单个命令创建单独的 jsh 文件并不是可行的解决方案。

同一篇文章的另一个解决方案是:echo "1+2"|jshell

temp=`echo 'String.format("%06d", 19)'|jshell`
echo $temp

哎哟输出

| Welcome to JShell -- Version 9 | For an introduction type: /help intro jshell> String.format("%06d", 19) $1 ==> "000019" jshell>

我期望 $temp 只打印 000019

最佳答案

默认情况下,与 JShell 交互时使用正常反馈模式,此模式打印命令输出、声明、命令和提示。阅读 Introduction to jshell feedback modes更多细节。

获取命令输出的步骤:

  1. 简洁反馈模式运行jshell以跳过命令和声明细节,它仍然会打印提示和值。

     $ echo 'String.format("%06d", 19)' | jshell --feedback concise
       jshell> String.format("%06d", 19)
       $1 ==> "000019"
    
  2. 使用 sed 从结果中过滤第二行-

    echo 'String.format("%06d", 19)' | jshell --feedback concise | sed -n '2p'
    
  3. 仅提取值并排除其他详细信息-

    echo 'String.format("%06d", 19)' | jshell --feedback concise | sed -n '2p' |sed -En 's/[^>]*>(.+)/\1/gp'
    

关于java - 如何从 shell 或 windows 命令行以内联方式执行 java jshell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46739870/

相关文章:

java - 写灰度图出错

java - 使用一些数组和循环的简化策划游戏

java - Admob 通过 Adwhirl : Not enough space to show ad! 想要 : 480, 75,有 : 480, 0

java - 将字符串转换为日历 - 日历是错误的日期

java - jshell中按Tab时出现 "Error on input: java.io.IOException: Resource temporarily unavailable"

java - 当我在 Windows cmd 中按下 BackSpace 按钮时,Jshell 崩溃

java - maven-release-plugin 是否与 Java 9 兼容?

java - Spliterator 跳过部分文本

java - 默认情况下,模块路径上有哪些系统模块?