0

I am trying to capture the elements of a string by splitting it using a delimiterusing a shell script,but I am not able to capture the elements properly if the string has any space among the words between the delimiters

eg:

`var=hello;my name is;john
IFS=';' read -ra data<<< "$var"
a=${data[0]}
b=${data[2]}
c=${data[4]}
echo $a
echo $b
echo $c`

while am able to capture "hello" in 'a' but "my name is " is not being captured in 'b',am I doing anything wrong ?

Sid
  • 61
  • 1
  • 9
  • 1
    Your assignment is a syntax error. You need quotes around `var='hello;my name is;john'`. With that, `echo "${data[1]}"` (not `[2]`, why do you use that?) produces `my name is` like you'd expect. Voting to close as typo / trivial. – tripleee Apr 03 '17 at 05:33
  • yes I missed to add quotes here,but if my string doesnt have any spaces it working fine – Sid Apr 03 '17 at 05:41
  • Then your shell isn't Bourne-compatible. In `sh` and compatible implentations like `bash`, an unquoted, unescaped semicolon acts as a statement separator. `var=moo;bar` results in `var` being set to `moo` and `bar` to be executed as a command. – tripleee Apr 03 '17 at 05:54

0 Answers0