【问题标题】:Counting words and characters in Bash without wc [duplicate]在没有 wc 的情况下计算 Bash 中的单词和字符 [重复]
【发布时间】:2016-01-10 22:13:09
【问题描述】:

我有一个这样的变量集:

sentence="a very long sentence with multiple       spaces"

我需要在不使用 wc 等其他程序的情况下计算有多少单词和字符。

我知道数单词可以这样完成:

words=( $sentence )
echo ${#words[@]}

但是我如何计算包括空格在内的字符呢?

【问题讨论】:

    标签: bash


    【解决方案1】:

    但是我如何计算包括空格在内的字符呢?

    计算字符串使用的长度:

    echo "${#sentence}"
    47
    

    【讨论】:

      【解决方案2】:

      您还可以将grep 与匹配所有内容的正则表达式一起使用:

      echo "this string" | grep -oP . | grep -c .
      

      【讨论】:

        【解决方案3】:

        在一行中使用awk

        echo this string | awk '{print length}'
        

        另一种将标准输入文本传送到awk的方法:

        awk '{print length}' <<< "this string"
        

        【讨论】:

          猜你喜欢
          • 2012-11-18
          • 1970-01-01
          • 2014-03-03
          • 1970-01-01
          • 1970-01-01
          • 2015-05-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多