If there is a string:
[[some_str,another_str],[some_str,the_str],[some_str,the_str],[some_str,whatever_str]]
And I want output like this:
another_str: 1
the_str: 2
whatever_str:1
How could I do that?
If there is a string:
[[some_str,another_str],[some_str,the_str],[some_str,the_str],[some_str,whatever_str]]
And I want output like this:
another_str: 1
the_str: 2
whatever_str:1
How could I do that?
# read strings into an array, excluding [, ] and , characters
IFS='[],' read -r -a strings <<<'[[some_str,another_str],[some_str,the_str],[some_str,the_str],[some_str,whatever_str]]'
# store counts in an associative array
declare -A counts=()
for string in "${strings[@]}"; do
[[ $string ]] || continue
(( 'counts[$string]' += 1 ))
done
# iterate over that associative array and print counters
for string in "${!counts[@]}"; do
echo "$string: ${counts[$string]}"
done
If you were willing to use awk, you could do something like this:
$ awk -F] -vRS="," '!(NR%2){++a[$1]}END{for(i in a)printf "%s: %s\n",i,a[i]}' <<<"[[some_str,another_str],[some_str,the_str],[some_str,the_str],[some_str,whatever_str]]"
whatever_str: 1
another_str: 1
the_str: 2
Set the field separator to ]
and the record separator to ,
. Count the occurrence of every second record. After all records have been processed, print the results.