How can I split a string into array in shell script?
I tried with IFS='delimiter' and it works with loops (for, while) but I need an array from that string.
How can I make an array from a string?
Thanks!
str=a:b:c:d:e
set -f
IFS=:
ary=($str)
for key in "${!ary[@]}"; do echo "$key ${ary[$key]}"; done
outputs
0 a
1 b
2 c
3 d
4 e
Another (bash) technique:
str=a:b:c:d:e
IFS=: read -ra ary <<<"$str"
This limits the change to the IFS variable only for the duration of the read command.
#!/bin/sh change to #!/bin/bashset -- $str; for element in "$@"; do echo $element; done. If you really need an array, you need to choose a different tool for the job.Found a solution that doesn't require changing the IFS or a loop:
str=a:b:c:d:e
arr=(`echo $str | cut -d ":" --output-delimiter=" " -f 1-`)
output:
echo ${arr[@]}
a b c d e
Combining the answers above into something that worked for me
set -- `echo $PATH|cut -d':' --output-delimiter=" " -f 1-`; for i in "$@"; do echo $i; done
gives
# set -- `echo $PATH|cut -d':' --output-delimiter=" " -f 1-`; for i in "$@"; do echo $i; done
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
#
set -- and then collate with useful stuff from the multiple answers given. This was for my own purposes but also share back if others had the same issue