bash
has parameter transformation operators to help debug problems like this:
var='Strin1##String2###String3##String4#####String5'
IFS="##" read -ra var1 var2 var3 var4 var5 var6 <<< "$var"
echo ${var1[@]@A}
...which uses the A
ssignment operator to print a declare
statement showing what's really in the array $var1
:
declare -a var1=([0]="Strin1" [1]="" [2]="String2" [3]="" [4]="" [5]="String3" [6]="" [7]="String4" [8]="" [9]="" [10]="" [11]="" [12]="String5")
There's thirteen items, which corresponds to each "side" of the twelve #
s in the $var
string. This is because the $IFS
variable does not understand user-assigned strings, it only looks at those individual characters in a string. So IFS="#######"
and IFS="##"
and IFS="#"
are all equivalent, at least so far as read
is concerned.
The simplest fix is to first run $var
through tr
's squeeze function to remove the repeating #
s:
var='Strin1##String2###String3##String4#####String5'
IFS="#" read -ra var1 var2 var3 var4 var5 var6 <<< "$(tr -s '#' <<< "$var")"
echo ${var1[@]@A}
Which outputs:
declare -a var1=([0]="Strin1" [1]="String2" [2]="String3" [3]="String4" [4]="String5")