基于正则表达式分隔符在shell脚本中将字符串拆分为数组



我有一个名为JAVA_OPTS的字符串变量,在shell脚本中有各种参数。

-Dmaven.repo.local=/home/wangc/.m2/repository -Dtestparameter="some   spaces" --add-exports=java.base/sun.nio.ch=ALL-UNNAMED

我想把它拆分成一个基于空格的数组,但不是转义双引号中定义的空格。例如,我想看到一个有3个元素的数组:

-Dmaven.repo.local=/home/wangc/.m2/repository
-Dtestparameter="some   spaces" 
--add-exports=java.base/sun.nio.ch=ALL-UNNAMED

我试过

IFS=' ' read -r -a array <<< "$JAVA_OPTS"

但它无法区分双引号之间的不同空格,并返回一个四元素数组作为:

-Dmaven.repo.local=/home/wangc/.m2/repository
-Dtestparameter="some
spaces" 
--add-exports=java.base/sun.nio.ch=ALL-UNNAMED

为什么需要regex解决方案?让shell本身解析这一点要容易得多。

array=(-Dmaven.repo.local=/home/wangc/.m2/repository -Dtestparameter="some   spaces" --add-exports=java.base/sun.nio.ch=ALL-UNNAMED)

在这里,通过字符串变量$JAVA_OPTS来提取值是错误的,这会使问题变得更加困难。

最新更新