简体   繁体   English

BEGIN 和 END 块像 awk 一样在 groovy 中

[英]BEGIN and END block in groovy like in awk

At https://issues.apache.org/jira/browse/GROOVY-1512 , a patch is available for executing BEGIN and END methods similar to awk or Perl.https://issues.apache.org/jira/browse/GROOVY-1512 上,有一个补丁可用于执行类似于 awk 或 Perl 的 BEGIN 和 END 方法。 This could be useful for shell piping scenarios such as summing a list of numbers.这对于壳管道方案很有用,例如对数字列表求和。

I tried various syntaxes using the current version of Groovy, but it does not execute.我使用当前版本的 Groovy 尝试了各种语法,但它没有执行。 Can somebody tell me what the correct syntax is and provide an example for it?有人能告诉我正确的语法是什么并提供一个例子吗?

To rephrase the question in detail.详细地重新表述这个问题。 If I have the following,如果我有以下内容,

my-desktop# du -s * | cut -f 1

4
1976
4
16
16
24
16
16
16
16
16
524
20
16
20
20
4
4
4
4
364
2356
4
5992
28
8

I want something like the following (inspired from awk) that would print its sum:我想要像下面这样的东西(灵感来自 awk)可以打印它的总和:

du -s * | cut -f 1 | groovy -a -n -e 'def sum; BEGIN{sum =0; }END {println sum;}sum=sum+split[0].toInteger()'

If the special BEGIN and END closures or functions are not implemented yet, then how do I print a sum of all the list of numbers piped in from other Unix commands?如果特殊的 BEGIN 和 END 闭包或函数尚未实现,那么如何打印从其他 Unix 命令输入的所有数字列表的总和?

运行 Groovy 1.8.4,答案如下

du -s * | groovy -a '\s+' -ne 'def begin() {sum = 0}; def end() {println sum}; sum += split[0] as Long'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM