I'm trying to split a string of space delimited words so that each word ends up on a separate line , but substrings enclosed in quotes or brackets should be treated as one word, even if they contain multiple words.
Example:
Lorem 'ipsum dolor sit' amet 'consecur' adipis [elit sed do] [eius] mod
should be converted into
Lorem
'ipsum dolor sit'
amet
'consecur'
adipis
[elit sed do]
[eius]
mod
Is there an elegant way to achieve this? So far I've come up with a solution that seems to work, but I find it a bit clumsy:
Code: Select all
string="Lorem 'ipsum dolor sit' amet 'consecur' adipis [elit sed do] [eius] mod"
for n in $string;do
case $n in
'['*']'|"'"*"'") # [eius] and 'consecur'
echo "$n"
;;
'['*|*']'|*"'"*)
if [[ -z $iscompound ]];then # [elit and 'ipsum
iscompound=1
sub+=$n' '
else # do] andr sit'
sub+=$n
echo "$sub"
[[ $n =~ ("'"|']') ]] && iscompound= sub=
fi
;;
*)
[[ $iscompound ]] && sub+=$n' ' || echo "$n" # dolor or Lorem
;;
esac
done
Is there a better way?