bash - 基于正则表达式分隔符将字符串拆分为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
解决方案
为什么需要正则表达式解决方案?让 shell 本身解析它要容易得多。
array=(-Dmaven.repo.local=/home/wangc/.m2/repository -Dtestparameter="some spaces" --add-exports=java.base/sun.nio.ch=ALL-UNNAMED)
通过字符串变量绕过值$JAVA_OPTS
在这里是错误的做法,并且使问题变得更加困难。
推荐阅读
- r - Using purrr and functions to perform linear regressions on a number of variables with random errors
- rust - Extracting MsgPack from String of bytes - rust
- tmux - Problem in tmux.conf with nested if or nested quotes
- python - Pythonic Way to Execute Action at a Threshold Value
- java - 下拉框值更改
- javascript - 从 JSON 数据格式化分组数据
- c# - UWP-xaml InkCanvas:有没有办法拒绝在特定区域上绘画?
- python - Comparing Two Lines In Opened Files With For Loops
- angular - Angular: Reset Array without reloading view in Ui
- zapier - Why doesn't my Zapier Integration Dynamic Field work?