Barath R
Barath R

Reputation: 209

Unable to split string stored in a variable containing $ as the delimiter

I'm trying to split this string and store substrings in separate variables as follows:

temp="one$two$three$fourfive"
IFS="$" read var1 var2 var3 var4 <<< "$temp"

When I echo var1 I get "one" but when I echo var2 there is no output. It works when I add a '\' before every $ sign but when I try to do it programmatically:

echo "$temp" | sed 's/$/\\$/g'

Output: one\$

How can I fix this?

Upvotes: 3

Views: 191

Answers (3)

agc
agc

Reputation: 8416

Using read isn't necessary, a bash array would be better than separate variables:

temp='one$two$three$fourfive'
var=(${temp//$/ })
printf '%s\n' ${var[@]}

Output:

one
two
three
fourfive

Upvotes: 1

Inian
Inian

Reputation: 85800

Your problem is with the original string temp where with double quotes, your rest of the strings two, three and fourfive are interpreted as shell variables.

Using single quotes on the temp string would let the variables to not to be expanded to an empty string.

temp='one$two$three$fourfive'

Also recommend using read with -r flag to not let not backslashes mangle your string

IFS='$' read -r var1 var2 var3 var4 <<< "$temp"

Upvotes: 4

Barmar
Barmar

Reputation: 781888

The problem isn't with reading them, it's when you assigned to temp in the first place. Variables are expanded inside double quotes, so it tries to use the values of $two, $three, etc. Since these variables don't exist, you just did:

temp="one"

You would have noticed this if you simply did:

echo "$temp"

You need to use single quotes instead of double quotes, so variables won't be expanded.

temp='one$two$three$fourfive'
IFS="$" read var1 var2 var3 var4 <<< "$temp"

Upvotes: 3

Related Questions