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!
Using the tr Command to Split a String Into an Array in Bash It can be used to remove repeated characters, convert lowercase to uppercase, and replace characters. In the bash script below, the echo command pipes the string variable, $addrs , to the tr command, which splits the string variable on a delimiter, ; .
In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.
The -a option of read will allow you to split a line read in by the characters contained in $IFS . #!/bin/bash filename=$1 while read LINE do echo $LINE | read -a done < $filename should it work?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With