0

With the following code:

string="[Git status]^functionGitStatus"
IFS='^' read -r -a array <<< "$string"
echo "${array[@]}"
echo "size: '${#array[@]}'"
for e in "${array[@]}"; do
   echo "'$e'"
done

It works as expected and shows:

[Git status] functionGitStatus
size: '2'
'[Git status]'
'functionGitStatus'

I did do a research and for example at

is possible use , (command with empty space)

If I try to accomplish the same approach:

string="[Git status]^ functionGitStatus"
IFS='^ ' read -r -a array <<< "$string"
echo "${array[@]}"
echo "size: '${#array[@]}'"
for e in "${array[@]}"; do
   echo "'$e'"
done

I got:

[Git status] functionGitStatus
size: '3'
'[Git'
'status]'
'functionGitStatus'

sadly not as expected (even when only exists one ocurrence with ^ )

I want to know if is possible to use a complete word-term as separator for example:

string="[Git status]-fn:-functionGitStatus"
IFS='-fn:-' read -r -a array <<< "$string"
echo "${array[@]}"
echo "size: '${#array[@]}'"
for e in "${array[@]}"; do
   echo "'$e'"
done

But it shows:

[Git status]      u ctio GitStatus
size: '9'
'[Git status]'
''
''
''
''
''
'u'
'ctio'
'GitStatus'

Seems is not possible or perhaps there is a special flag to interpret how complete word-term. If is not possible what other function would help in this scenario?

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
  • 3
    `IFS` is treated as a *set* of characters that can be used as delimiters, not a single multi-character delimiter. – chepner Feb 10 '22 at 15:25

1 Answers1

2

With bash parameter expansion and mapfile:

$ string='[Git status]-fn:-functionGitStatus'
$ mapfile -t array <<< "${string//-fn:-/$'\n'}"
$ echo "${array[@]}"
[Git status] functionGitStatus
$ echo "size: '${#array[@]}'"
2
$ for e in "${array[@]}"; do echo "'$e'"; done
'[Git status]'
'functionGitStatus'

Explanation: "${string//-fn:-/$'\n'}" is a bash parameter expansion with substitution: all (because // instead of /) -fn:- substrings in string are replaced by $'\n', that is, a newline (the $'...' syntax is documented in the QUOTING section of bash manual). <<< is the here-string redirection operator. It "feeds" the mapfilecommand with the result of the parameter expansion with substitution. mapfile -t array (also documented in the bash manual) stores its input in the bash array named array, one line per cell, removing the trailing newline character (-t option).

Renaud Pacalet
  • 25,260
  • 3
  • 34
  • 51
  • If you can add a brief explanation of the `mapfile -t array <<< "${string//-fn:-/$'\n'}"` line would be nice. Thank You – Manuel Jordan Feb 10 '22 at 17:30
  • 1
    I added some explanation but nothing replaces the bash manual (`man bash`) that you can search with patterns. For instance, if you type `man bash`, and then slash-`<<<` you'll find the here-string section. Same with `mapfile`. – Renaud Pacalet Feb 10 '22 at 18:00