Question

I have a variable length string which looks like the following:

-DFOO -DBAR="1 2 3" -DTEST="\"asdf asdf\""

Which I would like to split into several lines, using space as delimiter (except if they occur in quotes).

The expected result of the example is:

-DFOO
-DBAR="1 2 3"
-DTEST="\"asdf asdf\""

How can I do this using "normal" unix tool. I tried with AWK but without any luck, most references of solving this problem with AWK had a fixed number of arguments.

Was it helpful?

Solution

you want "normal" unix tool.:

awk:

awk -F' -' -v OFS='\n-' '$1=$1'

test

kent$  echo '-DFOO -DBAR="1 2 3" -DTEST="\"asdf asdf\""'|awk -F' -' -v OFS='\n-' '$1=$1'
-DFOO
-DBAR="1 2 3"
-DTEST="\"asdf asdf\""

sed

kent$  sed 's/ -/\n-/g' <<< '-DFOO -DBAR="1 2 3" -DTEST="\"asdf asdf\""'                 
-DFOO                                                                   
-DBAR="1 2 3"
-DTEST="\"asdf asdf\""

or grep

kent$  echo '-DFOO -DBAR="1 2 3" -DTEST="\"asdf asdf\""'|grep -oP -e'-[^-]*' 
-DFOO 
-DBAR="1 2 3" 
-DTEST="\"asdf asdf\""
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top