Equivalent of perl diamond/python fileinput in groovy? -


i looking function or operator (maybe library) mimics perl's diamond operator or python's fileinput.

of course check myself arguments, make sure each file , loop through, if none exists read stdin...but defeats purpose: create small unix command line scripts in seconds needs loop through files or stdin cat, grep, sed etc. not having write 30 lines boilerplate code...just 1 or 2 lines.

as far know, there not such built-in function/library.

anyway, if objective make scripts , loop through files or stdin, can create similar groovy lib. example:

fileinput.groovy:

class fileinput {     static void input(string[] args, closure c) {         if (args) {             args.collect { new file(it) }.findall { it.isfile() }.each { it.eachline(c) }         } else {             system.in.eachline(c)         }        } } 

then compile above , place resulting classes under ~/.groovy/lib:

$ groovyc -d ~/.groovy/lib fileinput.groovy 

and can use in scripts

test.groovy

import fileinput  fileinput.input(args) { println it.touppercase() } 

so that

$ groovy test.groovy example.txt line 1 line 2 line 3 

defaults stdin when there no file:

$ groovy test.groovy < example.txt line 1 line 2 line 3  $ cat example.txt | groovy test.groovy line 1 line 2 line 3  $ groovy test.groovy hello hello world world 

skips dirs:

$ groovy test.groovy example.txt testdir line 1 line 2 line 3 

and right (since testing isfile()) disregarding not existing files:

$ groovy test.groovy example.txt wrongfile.txt example.txt line 1 line 2 line 3 line 1 line 2 line 3 

Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -