0

How is it possible to split a string to an array?

#!/bin/sh

eg.

str="field 1,field 2,field 3,field 4"

The length of the arrays is various

Have found alot of solutions but they only works in bash

update

This only works if the length of the array has 4 values, but what if it has 10 values?

The for loop doesn't seem to work

arr=$(echo "field 1,field 2,field 3,field 4" | awk '{split($0,a,","); print a[1],a[2],a[3],a[4]}');

for value in ${arr[@]}
do
    echo "$value\n"
done
2
  • by what separator do you want to split string? , or ` ` Commented Feb 6, 2014 at 13:03
  • The plain POSIX shell does not support arrays at all. You need to use a shell (bash, zsh, probably others) that does. Commented Feb 6, 2014 at 14:17

2 Answers 2

2

To get the split into variables in dash (that doesn't support arrays) use:

string="field 1,field 2,field 3,field 4"
IFS=","
set -- $string
for val
do
  echo "$val"
done
Sign up to request clarification or add additional context in comments.

6 Comments

how can you assign all values to a variable? and what if the array is longer than 4 values?
the array returned by awk will be as long as there are fields in the input. I'm not sure what you mean about assigning the values to a variable
have updated the question.. in you exampe you only print up to 4 values, but what if the array has 10 values? The for loop doesn't seem to work either
so, bash supports arrays, dash doesn't so you are a bit restricted in what you can do. Updating answer.
thanks.. is there any way to run through each value with a loop?
|
0

In bash you can do this:

str="field 1,field 2,field 3,field 4"
IFS=, array=($str)

IFS is the input field separator.

Zsh is much more elegant

array=${(s:,:)str}

You can even do it directly

% for i in "${(s:,:)str[@]}"; do echo $i; done
field 1
field 2
field 3
field 4

4 Comments

Then use the first one
the first one (first two lines alone) returns an error test.sh: 4: test.sh: Syntax error: "(" unexpected
@clarkk You aren't using bash; your shell does not support arrays.
Run it as /bin/bash instead of /bin/sh

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.