3

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

2 Answers 2

6

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[@]}"
Sign up to request clarification or add additional context in comments.

3 Comments

Neat solution covering most of my requirements ! Thanks a lot !
Couldn't you make the loop head while IFS=, read -ra arr; do, and get rid of the next line?
It seems that the initialization line imageId=(); sessionId=(); is not necessary either. (Although it couldn't hurt!)
1
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.

2 Comments

Ok, so your splitting the string and storing them in an array. How do I store the entities in different arrays . I want to create arrays of imageID's , sessionID's etc. Can you please modify your code ?
set -A doesn't work for me (no -A option to set). The page you link to uses declare.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.