简体   繁体   中英

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. 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].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?

运行 Groovy 1.8.4,答案如下

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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