使用Ruby命令行的类似AWK的BEGIN和END [英] Awk-like BEGIN and END with Ruby command-line

查看:72
本文介绍了使用Ruby命令行的类似AWK的BEGIN和END的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于Ruby的一件很酷的事情是它具有像典型的Unix命令行工具一样的行为,能够做类似的事情(类似于官方文档中的示例):

One of the cool things about Ruby is its ability to behave like typical Unix command-line tools, to do things like (similar to the example from the official documentation):

$ echo "matz" | ruby -pe '$_.upcase!'
MATZ

另一方面,Awk可以对标准输入的行进行汇总,例如,对一系列数字求和:

Awk, on the other hand can perform an aggregation on lines from standard input, e.g., summing a sequence of numbers:

$ for (( i=0; $i < 50; i++ )); do echo $i; done | awk 'BEGIN { tot=0; } { tot += $0 } END { print tot }'
1225

我想知道是否有可能让Ruby来执行上述Awk BEGINEND块所实现的功能,以便能够执行类似的聚合操作.

I'd like to know if it's possible to get Ruby to do what is being achieved by the Awk BEGIN and END blocks above so as to be able to do similar aggregation operations.

推荐答案

seq 49 | ruby -pe 'BEGIN { $tot=0 }; $tot += $_.to_i; END { print $tot }'

这篇关于使用Ruby命令行的类似AWK的BEGIN和END的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆