I have a string
echo $STRING
which gives
first second third fourth fifth
basically a list separated spaces.
how do i take that string and make it an array so that
array[0] = first
array[1] = second
etc..
I have tried
IFS=' ' read -a list <<< $STRING
but then when i do an
echo ${list[@]}
it only prints out "first" and nothing else
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.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
Use sed 's/^ *//g', to remove the leading white spaces. There is another way to remove whitespaces using `sed` command. The following commands removed the spaces from the variable, $Var by using `sed` command and [[:space:]].
It's simple actually:
list=( $STRING )
Or more verbosely:
declare -a list=( $STRING )
PS: You can't export IFS and use the new value in the same command. You have to declare it first, then use it's effects in the following command:
$ list=( first second third )
$ IFS=":" echo "${list[*]}"
first second third
$ IFS=":" ; echo "${list[*]}"
first:second:third
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