Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am trying to extract command line arguments from a file. I am having trouble splitting on fields that are quoted with escaped quotes inside

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['-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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading