Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to convert a string with space delimited tokens to an array

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

like image 863
Dan Avatar asked Mar 22 '13 17:03

Dan


People also ask

How do I convert a string to an array in bash?

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, ; .

How do I split a string on a delimiter in bash?

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.

What is $@ in bash script?

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.

How do I remove spaces from a string in bash?

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:]].


1 Answers

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
like image 149
svckr Avatar answered Oct 16 '22 17:10

svckr