如果有字符串:
[[some_str,another_str],[some_str,the_str],[some_str,the_str],[some_str,whatever_str]]
我想要这样的输出:
another_str: 1
the_str: 2
whatever_str:1
我怎么能这样做?
答案 0 :(得分:4)
# 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
答案 1 :(得分:0)
如果你愿意使用awk,你可以这样做:
$ 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
将字段分隔符设置为]
,将记录分隔符设置为,
。计算每个第二条记录的发生次数。处理完所有记录后,打印结果。