How to read array from delimited text
use readarray with -d option to read the delimited
text as array in bash
#!/usr/bin/env bash# User inputsecho -n "Enter Number of elements: "read -r no_of_elementsecho -n "Enter delimiter: "read -r delecho -n "Enter array elements as delimited text: "readarray -n no_of_elements -d del elements# Outputecho ""echo "Array elements: "for item in elements[@];doecho itemdone;
Output of the above snippet is,
./test.shEnter Number of elements: 3Enter delimiter: ,Enter array elements as delimited text: 1,2,3,Array elements:1,2,3,
If we like to remove the delimiter captured as part of an array element we can pass -t option.
Note:
-tmust be passed before supplying the-doption.Eg,
readarray -t -n $no_of_elements -d $del elements-doption uses the delimiter to parse and split the array elements. So, it is mandatory to pass the delimiter after the last element