Skip to content

Specify source line from csv when calling up/creating an array

I have a csv with data such as:

L'Oreal, Apricot and Peach Conditioner, Sale
Sure, Camomile Deodorant Spray, Standard
Brut, Classic Aftershave, Sale 

I’ve written some code to turn each field into a variable, and also to create an array out of each word in field 2 (f2):


#read the csv and creates a variable for each field

while IFS=',' read -r f1 f2 f3 f4

#Create an array out of each word in field 2 which is the description field
read -a arr <<<$f2
#print the specified array- the first word is ${arr[0]}
echo ${arr[0]}

done < "$input"

My problem is now, because the file contains multiple lines I need some way of naming each array according to the line of data it was created from. At the moment when I echo ${arr[0]} it prints the first word from f2 of every line, when I would like to be able to be able to call up a specific line. EDIT: To clarify (sorry I’m a noob and didn’t explain very well) I would like to somehow change my code so that rather than creating an array for each separate word in f2 throughout the file, I want to create an array for each word in f2 on a line by line basis and somehow be able to display the line of the csv it came from.



My answer is just guessing, but it maybe can help you. Maybe clarify your question that so I can address my answer better.


# it prints specyfic argument of array: array guide
    local lineNo="$1"
    echo "${inputLines[$lineNo]}"

# gets specyfic block of line csv's file
    local lineNo="$1"
    local blockNo="$2"

    # split string into array by read function
    # look at:
    IFS=',' read -r -a block <<< "$(getLine $lineNo)"
    echo "${block[$blockNo]}"

    local lineNo="$1"
    local blockNo="$2"
    local elementNo="$3"

    read -r -a element <<< "$(getBlock $lineNo $blockNo)"
    echo "${element[$elementNo]}"

# read file into an array
# based on nhed response:
IFS=$'rn' GLOBIGNORE='*' command eval 'inputLines=($(cat $input))'
echo "Loaded ${#inputLines[@]} lines."

getLine 0         # print line of csv
getBlock 0 1      # print block of csv
getElement 0 1 2  # print element of csv
User contributions licensed under: CC BY-SA
10 People found this is helpful