User0911
User0911

Reputation: 1582

Bash read csv file using awk and save output in array

I have an excel file and column 10 has multiple values like below,

Designation Header
-----------------
Student
Teacher
Teacher
Organization Director
Organization Director
Organization Head
Student
Organization Head
Organization Director
Teacher

I am trying to get the unique values from this column and the number of rows corresponding to each unique value in an associative array.

Here is the command I am using to get the unique value and number of rows,

awk -F',' 'NR>1{print $10}' Sorted_File.csv | sort | uniq -c

This gives me output as below,

 2 Student
 3 Teacher
 3 Organization Director
 2 Organization Head

How do I save this output in an associative array i.e key-value pair?

Upvotes: 0

Views: 243

Answers (2)

tshiono
tshiono

Reputation: 22012

Another bash version without awk:

declare -A counts
while IFS=, read -r -a ary; do
    (( counts[${ary[9]}]++ ))
done < <(tail -n +3 Sorted_File.csv)

declare -p counts

Upvotes: 1

Shawn
Shawn

Reputation: 52344

In bash, it'd be something like:

#!/usr/bin/env bash

declare -A counts
while read -r cnt what; do
    counts[$what]=$cnt
done < <(awk -F',' 'NR>1{print $10}' Sorted_File.csv | sort | uniq -c)

declare -p counts

Basically, read the output of your original pipeline in a loop, adding each pair of values to the associate array.

Upvotes: 0

Related Questions