llusca
llusca

Reputation: 13

split string with quote and space into array

I don't know how to slit string containing space 'but not those between quote' into array:

llusca@debian:~$ my_string='key1="value1" key2="va:lu:e2" key3="value with spaces"'
llusca@debian:~$ IFS='"\ ' arr=($my_string)
llusca@debian:~$ for i in ${arr[@]}; do echo $i; done
key1=
value1
key2=
va:lu:e2
key3=
value
with
spaces

expected:

key1="value1"
key2="va:lu:e2"
key3="value with spaces"

How can I do ? Shall I use awk or other regex (the number of key/value is not fixed) ?

Upvotes: 0

Views: 80

Answers (1)

Philippe
Philippe

Reputation: 26697

Assuming you don't have escaped double quotes inside double quotes, this can be done with bash regex :

#!/usr/bin/env bash

my_string='key1="value1" key2="va:lu:e2" key3="value with spaces"'
pattern='([^=]+)="([^"]+)" *'

declare -A result # associative array
while [[ $my_string =~ $pattern ]]; do
    result[${BASH_REMATCH[1]}]=${BASH_REMATCH[2]}
    my_string=${my_string:${#BASH_REMATCH[0]}} # update my_string
done

declare -p result

Upvotes: 3

Related Questions