Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string (stored in a variable) into multiple words using spaces but not the spaces within double quotes

Tags:

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.

like image 662
Zettt Avatar asked Jun 27 '13 08:06

Zettt


1 Answers

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
like image 79
iruvar Avatar answered Sep 18 '22 03:09

iruvar