HOWTO: CSV string in Bash (or using any other separator)


#1

Suppose you have a string of values separated by a comma (or, in fact, any other character too)

$ string=“192.168.12.122,24,192.168.12.1,eth0,794,192.168.12.1”

Now, to be able to access each value by its position number we must turn this string into an array by defining Input Field Separator and using array population construct a=( $v ) [mind the whitespaces after the opening and before closing brackets]

$ IFS="," array=( $string )

Try echoing array elements:

$ echo ${array[3]}
eth0
$ echo ${array[0]}
192.168.12.122

Using read in a while-loop it should be trivial to construct a multidimensional array of array[row][value] kind.