Using parameter substitution on a Bash array

As far as I can see, there's no need to read it into a bash array to create that output:

$ sed 's/[ "]//g; s/,/ /; s/,//g; s/ /,/; s/.*/|ELEMENT|&|/' <file
|ELEMENT|10,this|
|ELEMENT|20,is|
|ELEMENT|30,all|
|ELEMENT|40,I|
|ELEMENT|50,need2|
|ELEMENT|60,see|

The sed expression deletes spaces and double quotes, replaces the first comma with a space (there are no other spaces in the string at this point), deletes all other commas, restores the first comma, and the prepends and appends the extra data.

Alternatively, with GNU sed:

sed 's/[ "]//g; s/,//2g; s/.*/|ELEMENT|&|/' <file

(standard sed does not support the combination of 2 and g as flags to the s command).


I would remove what you need to remove using sed before loading into the array (also note the lower case variable names, in general it is best to avoid capitalized variables in shell scripts):

#!/bin/bash
readarray -t array< <(sed 's/"//g; s/  *//g; s/,/"/; s/,//g; s/"/,/' "$1")
for element in "${array[@]}";do
    echo "|ELEMENT|$element|"
done

This produces the following output on your example file:

$ foo.sh file 
|ELEMENT|10,this|
|ELEMENT|20,is|
|ELEMENT|30,all|
|ELEMENT|40,I|
|ELEMENT|50,need2|
|ELEMENT|60,see|

If you really must use parameter substitution, try something like this:

#!/bin/bash
readarray -t array< "$1"
array=( "${array[@]// /}" )
array=( "${array[@]//\"/}" )
array=( "${array[@]/,/\"}" )
array=( "${array[@]//,/}" )
array=( "${array[@]/\"/,}" )

for element in "${array[@]}"; do
    echo "|ELEMENT|$element|"
done

ELEMENT='50,n,e,e,d,2'
IFS=, read -r first rest <<<"$ELEMENT"
printf "%s,%s\n" "$first" "${rest//,/}"
50,need2

Get out of the habit of using ALLCAPS variable names. You'll eventually collide with a crucial "system" variable like PATH and break your code.