Skip to content
Advertisement

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):

#!/bin/bash
input="/home/abbie/Documents/Scripts/test.csv"

#read the csv and creates a variable for each field

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

do
#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.

Advertisement

Answer

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

#!/bin/bash
input="test.csv"

# it prints specyfic argument of array: array guide http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html
getLine()
{
    local lineNo="$1"
    echo "${inputLines[$lineNo]}"
}

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

    # split string into array by read function
    # look at: http://stackoverflow.com/questions/10586153/split-string-into-an-array-in-bash
    IFS=',' read -r -a block <<< "$(getLine $lineNo)"
    echo "${block[$blockNo]}"
}

getElement() 
{
    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: http://stackoverflow.com/questions/11393817/bash-read-lines-in-file-into-an-array
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
Advertisement