-1

I have a string variable called JAVA_OPTS with various parameters in shell script.

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

I'd like to split it into an array based on spaces, but not the space defined in escaped double quotes. For example I'd like to see an array with 3 elements:

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

I have tried

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

But it can't tell the different space between double quotes, and return a four elements array as:

-Dmaven.repo.local=/home/wangc/.m2/repository
-Dtestparameter="some
spaces" 
--add-exports=java.base/sun.nio.ch=ALL-UNNAMED
tripleee
  • 175,061
  • 34
  • 275
  • 318
user1684651
  • 390
  • 1
  • 8
  • 21

1 Answers1

0

Why do you require a regex solution? Getting the shell itself to parse this is significantly easier.

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

Detouring the values via a string variable $JAVA_OPTS is precisely the wrong thing to do here, and makes the problem signicicantly harder.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • I want to keep double quotes as -Dtestparameter="some spaces", your example would swallow the double quotes and store it as -Dtestparameter=some spaces. please try `array=(-Dmaven.repo.local=/home/wangc/.m2/repository -Dtestparameter=\"some spaces\" --add-exports=java.base/sun.nio.ch=ALL-UNNAMED)` – user1684651 Jan 11 '21 at 09:02
  • 2
    I'm guessing you are confused about what the quotes mean. Once the shell has parsed them, the actual string doesn't have any quotes. – tripleee Jan 11 '21 at 09:04