bash - 有效编码以计算文件中的大写字符
问题描述
我想计算文件中所有大写字符 AZ 。
我将文件作为参数,然后在整个文件中搜索每个字母并总结我的结果。我的代码运行良好,但是否有另一种方法可以提高效率,而不使用循环?
sum=0
for var in {A..Z}
do
foo="$(grep -o $var "$1"| wc -l)"
sum=$((sum+foo))
done
我试图这样做,但它给了我错误的结果,因为它的计数空间和结束线。
cat "$1" | wc -m
解决方案
我们确实可以避免使用多个程序来计算文件中的大写字母,这可以用一个程序轻松完成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.
推荐阅读
- vue.js - 带有 VueJS 自动完成的元素 UI:避免突变 A 道具(Vue 警告)
- regex - RegEx to check 24 hours time format fails
- r - 为什么梯度下降结果与 lm 结果相差如此之远?
- javascript - chrome 扩展 - 读取 crdownload 文件的第一个字节
- javalite - Javalite for Microservice 项目,是否提供应用程序跟踪/监控支持?
- python - Python Selenium - 尝试/排除不起作用
- laravel - 将父模型的数据提取到 static::saving() 启动函数中
- azure-devops - 发布成功后触发发布
- javascript - 根据首先返回的异步调用执行函数
- java - 如何查找是否在会话中添加或删除了所有数据?