I'm trying to write a, for me, complicated script where my goal is to do the following. I have a string coming in that looks like this:
2012 2013 "multiple words"
My goal is to put each of these onto an array split by spaces, but only for single word matches, not those surrounded by double quotes. Those should be considered one word. So my idea was to do this in two steps. First match those words that are multiples, remove those from the string, then in another iteration split by white space.
Unfortunately I can't find help on how to echo
the match only. So far I have this:
array=$(echo $tags | sed -nE 's/"(.+)"/\1/p')
But this would result in (on OS X):
2012 2013 multiple words
Expected result:
array[1]="2012"
array[2]="2013"
array[3]="multiple words"
How would I go about this sort of problem?
Thanks.
eval
is evil, but this may be one of those cases where it comes handy
str='2012 2013 "multiple words"'
eval x=($str)
echo ${x[2]}
multiple words
Or with more recent versions of bash
(tested on 4.3)
s='2012 2013 "multiple words"'
declare -a 'a=('"$s"')'
printf "%s\n" "${a[@]}"
2012
2013
multiple words
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With