【问题标题】:count number of times a character appears in a string in unix计算一个字符在 unix 中的字符串中出现的次数
【发布时间】:2016-04-04 19:57:09
【问题描述】:

在unix的命令行中,无论如何计算一个字符在字符串中出现的次数。

例如:字符串="你好" "l" 这应该返回 2

string = "你好" "k" 这应该返回 0

字符串 = "你好" "H" 这应该返回 0

谢谢

【问题讨论】:

  • sedwc 可以工作。
  • > grep -o "."
  • 你正在寻找“.”,这是一个匹配任何字符的正则表达式。如果要匹配“点”字符,请尝试grep -o "\."
  • grep -o "some_string" filename | wc -l 或者如果基于 ${string} 变量进行检查,您将运行以下... echo ${string} | grep -o "some_string" | wc -l

标签: linux unix


【解决方案1】:

在 $STRING 中寻找字符 l

echo $STRING| grep -o l | wc -l

【讨论】:

    【解决方案2】:
    echo "Hello" | tr -cd "l" | wc -c
    

    修剪删除“l”的恭维;计算字符数。

    【讨论】:

      【解决方案3】:

      使用带有字符串 hello 的 Bash 内置函数并查找“l”可以通过以下方式完成:

      strippedvar=${string//[^l]/}
      echo "char-count: ${#strippedvar}"
      

      首先从字符串中删除所有不同于 l 的字符。
      你显示剩余变量的长度。

      替换中的字母可以由 var 给出,如下循环所示:

      string=hello
      for ch in a b c d e f g h i j k l m; do
          strippedvar=${string//[^$ch]/}
          echo "The letter ${ch} occurs ${#strippedvar} times"
      done
      

      输出:

      The letter a occurs 0 times
      The letter b occurs 0 times
      The letter c occurs 0 times
      The letter d occurs 0 times
      The letter e occurs 1 times
      The letter f occurs 0 times
      The letter g occurs 0 times
      The letter h occurs 1 times
      The letter i occurs 0 times
      The letter j occurs 0 times
      The letter k occurs 0 times
      The letter l occurs 2 times
      The letter m occurs 0 times
      

      【讨论】:

        猜你喜欢
        • 2011-07-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-13
        • 2014-04-24
        • 2017-10-09
        • 2010-11-12
        相关资源
        最近更新 更多