【发布时间】:2023-03-31 09:27:01
【问题描述】:
如果有字符串:
[[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
我该怎么做?
【问题讨论】:
标签: linux string bash substring
如果有字符串:
[[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
我该怎么做?
【问题讨论】:
标签: linux string bash substring
# 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
【讨论】:
IFS 泄漏到重定向,并且是4.3 中修复的4.2 错误。所以是的,这很好。 (为了记录,我从来没有打算质疑这个事实。)
如果你愿意使用 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
将字段分隔符设置为],将记录分隔符设置为,。计算每秒记录的出现次数。处理完所有记录后,打印结果。
【讨论】: