【问题标题】:Processing string in BASH and count the number of a substring beeing seen在 BASH 中处理字符串并计算看到的子字符串的数量
【发布时间】: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


    【解决方案1】:
    # 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
    

    【讨论】:

    • 关联数组需要 bash 4 或更高版本。还有一些 IFS/read/heredoc/herestring 错误已在某些 bash 4+ 版本中修复,可能与此处相关也可能不相关(不幸的是,我忘记了细节)。
    • 编辑后的当前版本(感谢@gniourf_gnioruf)可以在 4.0.35 上使用,所以我认为我们不依赖这里的任何最新修复。
    • 看起来我正在考虑的问题是将IFS 泄漏到重定向,并且是4.3 中修复的4.2 错误。所以是的,这很好。 (为了记录,我从来没有打算质疑这个事实。)
    • 有趣——我没有听说过那个错误;会尽量记住它。谢谢!
    • 不是最好的资源,但至少是一些东西。 stackoverflow.com/questions/24929819/ifs-change-with-bash-4-2
    【解决方案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
    

    将字段分隔符设置为],将记录分隔符设置为,。计算每秒记录的出现次数。处理完所有记录后,打印结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2023-03-28
      • 1970-01-01
      • 2016-05-24
      相关资源
      最近更新 更多