Separating a string with a colon

I am trying to split a string by ":" and store it in an array, so something like: b: c: d: x: y: z will be stored in an array that contains a, b, c, d, x, y , z as elements.

What I wrote

IFS = ':' read - r -a ARR <<< "$INFO" 

      

where INFO is a string that is read from a file containing multiple lines in the above format.

I am getting the error "IFS: command not found".

I read them like this:

while read INFO

      

Finally, when I try to assign the first element in the array to a variable, I get the error:

export NAME = $INFO[0] 

      

the two errors I am getting here are export: '=' not a valid identifier

andexport: '[0]: not a valid identifier

I am relatively new to bash.

+3


source to share


2 answers


The main problem is that your code contains spaces in places where they are not allowed. For example, the following is perfectly accurate syntax (although it does not follow the POSIX conventions for variable naming , which recommends using lowercase characters for application-specific names):

info_string='a:b:c:d:x:y:z'
IFS=: read -r -a info_array <<< "$info_string" 

      



Likewise, when dereferencing, you need curly braces, and (again) cannot put spaces around =

:

name=${info_array[0]}

      

+3


source


It works:

s=a:b:c:d #sample string
IFS=:
a=( $s ) #array
printf "'%s' " "${a[@]}" #prints 'a' 'b' 'c' 'd' 

      

Syntax for getting the nth element in an array



${array_name[$index]}

      

(Requires curls), so you need export NAME="${INFO[0]}"

(the assignment is usually not necessary to specify, however export

, declare

, local

and the like, it is best to quote).

https://www.lukeshu.com/blog/bash-arrays.html is a good guide to working with bash arrays.

+1


source







All Articles