开发者

BEGIN and END block in groovy like in awk

开发者 https://www.devze.com 2023-02-16 19:29 出处:网络
At https://issues.apache.org/jira/browse/GROOVY-1512, a patch is available for executing BEGIN and END methods similar to awk or Perl. This could be useful for shell piping scenarios such as summing a

At https://issues.apache.org/jira/browse/GROOVY-1512, a patch is available for executing BEGIN and END methods similar to awk or Perl. 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. 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:

du -s * | cut -f 1 | groovy -a -n -e 'def sum; BEGIN{sum =0; }END {println sum;}sum=sum+split[0].to开发者_高级运维Integer()'

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?


Running Groovy 1.8.4, the answer is given as

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

精彩评论

暂无评论...
验证码 换一张
取 消