Home > Enterprise >  How to count occurrences of a phrase in Bash?
How to count occurrences of a phrase in Bash?

Time:11-20

I have an array:

ABC
GHI
XYZ
ABC
GHI
DEF
MNO
XYZ 

How can I count the occurrences of each phrase in this array?

(Can I use a for loop?)

Expected output:

2 ABC
1 DEF
2 GHI
1 MNO
2 XYZ

Thank you so much!

CodePudding user response:

sort file.txt | uniq -c should do the job.

If you mean an array in bash, echo them:

array=(ABC GHI XYZ ABC GHI DEF MNO XYZ)
for i in "${array[@]}"; do echo "$i"; done | sort | uniq -c

Output:

  2 ABC
  1 DEF
  2 GHI
  1 MNO
  2 XYZ

CodePudding user response:

Using pure bash and an associative array to hold the counts:

#!/usr/bin/env bash

declare -a words=(ABC GHI XYZ ABC GHI DEF MNO XYZ) # regular array
declare -A counts # associative array

# Count how many times each element of words appears
for word in "${words[@]}"; do
    counts[$word]=$(( ${counts[$word]:-0}   1 ))
done

# Order of output will vary
for word in "${!counts[@]}"; do
    printf "%d %s\n" "${counts[$word]}" "$word"
done
  •  Tags:  
  • bash
  • Related