2

I am writing output of awk to array in bash like so:

ARR=$(( awk '{print $2}' file.txt ))

Imagine the content of file.txt is:

A B
A B
A C
A D
A C
A B

What I want is number of repetition of each string in second column like:

B: 3
C: 2
D: 1

Any other solution rather than arrays and awk is welcome.

2 Answers 2

4

Using awk you can do:

awk '{c[$2]++} END{for (i in c) print i ":", c[i]}' file
B: 3
C: 2
D: 1
Sign up to request clarification or add additional context in comments.

1 Comment

Alternative solution is: sort -k2 file | uniq -f1 -c |awk '{print $3 ":", $1}'
1

Other solution I found:

awk '{print $2}' file.txt | sort | uniq -c | sort -nr | while read count name
do
        if [ ${count} -gt 1 ]
        then
                echo "${name} ${count}"
        fi
done

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.