Sample Header Ad - 728x90

bash - slice quoted substrings delimited by spaces into array

0 votes
4 answers
189 views
following example:
string=" 'f o o' 'f oo' 'fo o' "
array=($string)
echo "${array}"
outputs:
'f
while the expected output is:
'f o o'
The only solution I came with is by changing the delimiter to newline (rather than space):
IFS=$'\n'
string="'f o o' # 'f oo' # 'fo o' #"
array=($(echo "$string" | tr '#' '\n'))
echo "${array}"
outputs:
'f o o'
which outputs the expected result, however this requires to set a custom delimiter in string and it's will invoke a new subprocess on each call. I would like to see a better solution than this, thanks you! **Edit:** The above example string should be enough, but since some has asked what the file contents looks like, it's something similar to this:
'magic1' 'some text' 'another simple text' 'some t£xt'
'magic2' 'another line with simple text' 'foo bar' 'yeah another substring'
'magic3' 'so@m{e$%& te+=*&' 'another substring' 'here is the substring'
'magic4' 'why not another line !' 'yeah I like that' 'the substring yeah !!!'
Even more details (as some users requested): there is a custom function which uses grep to return the line from the above file by using a magic substring. for example my find function similar to this:
_find()
{
   string="$(grep "$1" "$file")"
}
then I call it like this:
_find "magic2"
echo "$string"
which outputs:
'magic2' 'another line with simple text' 'foo bar' 'yeah another substring'
P/S: each substring is delimited by space, and each substring are quoted with single quotes. editing the _find is not possible since it's used by other functions. please see the comments for more.
Asked by Zero (39 rep)
Jan 5, 2025, 12:30 PM
Last activity: Jan 7, 2025, 12:53 PM