Home > database >  Bash and IFS: string split to an array with specific separator based on a complete word-term
Bash and IFS: string split to an array with specific separator based on a complete word-term

Time:02-11

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?

CodePudding user response:

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).

  • Related