首页 > 解决方案 > 有效编码以计算文件中的大写字符

问题描述

我想计算文件中所有大写字符 AZ 。

我将文件作为参数,然后在整个文件中搜索每个字母并总结我的结果。我的代码运行良好,但是否有另一种方法可以提高效率,而不使用循环?

sum=0
for var in {A..Z}
do
    foo="$(grep -o $var "$1"| wc -l)"
    sum=$((sum+foo))
done

我试图这样做,但它给了我错误的结果,因为它的计数空间和结束线。

cat  "$1" | wc -m

标签: bash

解决方案


我们确实可以避免使用多个程序来计算文件中的大写字母,这可以用一个程序轻松完成awk,它会节省我们一些周期,而且应该更快。

请您尝试以下操作。

awk '
{
  count+=gsub(/[A-Z]/,"&")
}
END{
  print "Total number of capital letters in file are: " count
}
'  Input_file

如果您想将其作为以 Input_file 作为参数的脚本运行,请将 Input_file$1也更改为。

说明:为上述代码添加说明,仅用于说明目的,不用于运行(以下)。

awk '                                                                   ##Starting awk program here.
{
  count+=gsub(/[A-Z]/,"&")                                              ##Creating a variable named count whose value will be keeping adding to itself, each time a substitution done from gsub.
                                                                        ##where gsub is awk out of the box function to substitute.
                                                                        ##Using gsub I am substituting each capital letter with itself and adding its count to count variable.
}
END{                                                                    ##Starting END block for this awk program. which will be executed once Input_file is done with reading.
  print "Total number of capital letters in file are: " count           ##Printing total number of capital letters which are there in count variable.
}
'  Input_file                                                           ##mentioning Input_file name here.

推荐阅读