Reputation: 12717
I have a multiline string which I want to transform into an array by using a single delimiter |
. However, when setting IFS=|
it will stop right before a new line appears:
IFS='|' read -a VARS <<< "var1|var2|var3
var4|var5|var6
var7|var8|var9"
echo ${VARS[@]}
#output => var1 var2 var3
I am wondering why the remaining lines won’t be evaluated and how to prevent that of happening, being able to assign every variable regardless the presence of a new line?
Upvotes: 1
Views: 912
Reputation: 5062
In bash, the proper syntax to write multiline strings is the following :
IFS='|' read -a VARS <<< "var1|var2|var3 \
var4|var5|var6 \
var7|var8|var9"
echo ${VARS[@]}
#>var1 var2 var3 var4 var5 var6 var7 var8 var9
#However, you will have
echo "${VARS[@]}"
#>var1 var2 var3 var4 var5 var6 var7 var8 var9
If you want to write your string as a multiline one and remove completely spaces, you could add |
to your existing $IFS
instead of erasing it
IFS=$IFS'|' read -a VARS <<< "var1|var2|var3 \
var4|var5|var6 \
var7|var8|var9"
echo "${VARS[@]}"
#>var1 var2 var3 var4 var5 var6 var7 var8 var9
Upvotes: 3
Reputation: 75458
Set your IFS
to |
and \n
and use -d
to use another delimiter besides newline. You also need to keep your values intact. Spaces also get to be included.
IFS=$'|\n' read -d '' -a VARS <<< "var1|var2|var3
var4|var5|var6
var7|var8|var9"
read
by default only reads up to the first newline character unless changed by -d
. ''
is also synonymous to $'\0'
as an argument to it.
Spaces (including newlines) inside double-quotes are not silently ignored. They are also included literally as a value.
So perhaps what you really should have done is:
IFS='|' read -a VARS <<< "var1|var2|var3|var4|var5|var6|var7|var8|var9"
Upvotes: 5