I have the following file
argsfile
-e "my_var=\"this string has spaces\"" -e "my_var2=\"this one too\""
I need to be able to split this input into an array like so:
['-e', '"my_var=\"this string has spaces\""', '-e', '"my_var2=\"this one too\""' ]
I think this would also be fine
['-e', 'my_var="this string has spaces"', '-e', 'my_var2="this one too"' ]
In other words, I want to preserve the spaces within fields that are quoted, and I want to ignore escaped quotes for the purposes of splitting.
Python or Perl answers would also be great as long as I can execute them inside Bash code.
I’ve tried awk with FPAT of varying degrees of complexity, grep, read, and xargs. I can’t seem to figure out how to do this with any of these tools or any combination of them.
For example, grep -Eo "\S+|'.*'|\".*\" is too greedy: it splits on the first -e just fine, but then it treats the entire rest of the string as one element because of the double quotes surrounding my_var=\"this string has spaces\""', '-e', '"my_var2=\"this one too\".
Other things I’ve tried like xargs or awk also end up getting results that chop off the first -e and then just push the rest of the string into the first element of the array, or I get results that split on whitespace regardless of quotes.
Is this even possible to do?
>Solution :
Since this input is quoted in shell manner, it is best handled by the shell:
eval name=($(<argsfile))
There you have the array name.