anirudh_raja
anirudh_raja

Reputation: 379

Splitting string separated by comma into array values in shell script?

My data set(data.txt) looks like this [imageID,sessionID,height1,height2,x,y,crop]:

1,0c66824bfbba50ee715658c4e1aeacf6fda7e7ff,1296,4234,194,1536,0
2,0c66824bfbba50ee715658c4e1aeacf6fda7e7ff,1296,4234,194,1536,0
3,0c66824bfbba50ee715658c4e1aeacf6fda7e7ff,1296,4234,194,1536,0
4,0c66824bfbba50ee715658c4e1aeacf6fda7e7ff,1296,4234,194,1536,950

These are a set of values which I wish to use. I'm new to shell script :) I read the file line by line like this ,

cat $FILENAME | while read LINE
do
string=($LINE)
# PROCESSING THE STRING
done

Now, in the code above, after getting the string, I wish to do the following : 1. Split the string into comma separated values. 2. Store these variables into arrays like imageID[],sessionID[].

I need to access these values for doing image processing using imagemagick. However, I'm not able to perform the above steps correctly

Upvotes: 3

Views: 10710

Answers (2)

anubhava
anubhava

Reputation: 784898

set -A doesn't work for me (probably due to older BASH on OSX)

Posting an alternate solution using read -a in case someone needs it:

# init all your individual arrays here
imageId=(); sessionId=();

while IFS=, read -ra arr; do
    imageId+=(${arr[0]})
    sessionId+=(${arr[1]})
done < input.csv

# Print your arrays
echo "${imageId[@]}"
echo "${sessionId[@]}"

Upvotes: 6

Satya
Satya

Reputation: 8881

oIFS="$IFS"; IFS=',' 
set -A str $string
IFS="$oIFS"

echo "${str[0]}";
echo "${str[1]}";
echo "${str[2]}";

you can split and store like this

have a look here for more on Unix arrays.

Upvotes: 1

Related Questions