Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string by colon

Tags:

arrays

bash

unix

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

What I have written is

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

where INFO is a string which is being read in from a file containing multiple strings in the aforementioned format.

I get an error saying "IFS: command not found".

I am reading them in this way:

while read INFO

Lastly when I try to assign the first element in the array to a variable, I am getting an error:

export NAME = $INFO[0] 

the two errors I get here are export: '=' not a valid identifier and export: '[0]: not a valid identifier

I am relatively a newcomer to bash.

like image 653
Teja Magapu Avatar asked Mar 28 '26 20:03

Teja Magapu


2 Answers

The basic problem here is that your code contains spaces in places where they aren't allowed. For instance, the following is perfectly fine syntax (though it fails to comply with POSIX conventions on variable naming, which advises lowercase characters be used for application-defined names):

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

Similarly, on a dereference, you need curly braces, and (again) can't put spaces around the =:

name=${info_array[0]}
like image 189
Charles Duffy Avatar answered Apr 02 '26 03:04

Charles Duffy


This works:

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

The syntax to get the n-th item in an array is

${array_name[$index]}

(The curlies are required), so you need export NAME="${INFO[0]}" (assignments normally don't need to be quoted, however with export, declare, local, and similar, it's better to quote).

https://www.lukeshu.com/blog/bash-arrays.html is a good tutorial on how bash arrays work.

like image 25
PSkocik Avatar answered Apr 02 '26 04:04

PSkocik