首页 > 解决方案 > 基于正则表达式分隔符将字符串拆分为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

标签: bashshellscriptingescaping

解决方案


为什么需要正则表达式解决方案?让 shell 本身解析它要容易得多。

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

通过字符串变量绕过值$JAVA_OPTS在这里是错误的做法,并且使问题变得更加困难。


推荐阅读