5

As I said the title. I tried this code:

    areasArray=()

    while IFS= read -r line
    do
        areaName="$(awk -F ";" '{print $3}')"
        echo $areaName

        if [[ ! " ${areasArray[@]} " =~ " $areaName " ]]; then
            areasArray+=($areaName)
            echo ${areasArray[*]}
        fi
    done < $reportFile

$reportFile refers to a CSV file that looks like this:

something;something;US
something;something;US
something;something;UK
something;something;FR
something;something;UK
something;something;FR

And the array will looks like this: US US UK FR UK FR. But I want every zone to be added only if it's not already there. So it should looks like this: US UK FR. How can I do that? Thanks.

1 Answer 1

7

If you need to perform lookup, use an associative array, not an indexed array. Basically, you'll use the keys of the associate array like a set.

declare -A areasArray

while IFS=";" read _ _ areaName _; do
    if [[ ! -v areasArray[$areaName] ]]; then
        areasArray[$areaName]=
    fi
done < "$reportFile"

Unless there is a specific action you want to take only if the key isn't already present, you can skip the if; areasArray[$areaName]= is idempotent.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't understand what areasArray[$areaName]= is supposed to do... How should I add my areas to my array, then?
It maps the area just read to an empty string. We aren't interested in the values associated with the keys, just the keys (areas) themselves. You can iterate over the areas later with something like for area in "${!areasArray[@]}"; do ... ;done.
@EvanCarroll What version of bash are you using? 4.2 (maybe 4.3? I don't recall) is required for -v to work with array indexing. I'm intentionally not storing area names as values in the array, though, only as indices.

Your Answer

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