0

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?

2
  • Well, sh doesn't have associate arrays.... are you targeting bash or zsh? Commented Jul 26, 2021 at 2:35
  • Yes, bash should be ok Commented Jul 26, 2021 at 2:44

2 Answers 2

1

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

Comments

0

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.

Comments

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.