Is there an API for grep, pipe, cat in groovy?
Asked
Active
Viewed 8,816 times
1 Answers
20
Not sure I understand your question.
Do you mean make system calls and pipe the results?
If so, you can just do something like:
println 'cat /Users/tim_yates/.bash_profile'.execute().text
To print the contents of a file
You can pipe process output as well:
def proc = 'cat /Users/tim_yates/.bash_profile'.execute() | 'grep git'.execute()
println proc.text
If you want to get the text of a File
using standard Groovy API calls, you can do:
println new File( '/Users/tim_yates/.bash_profile' ).text
And this gets a list of the lines in a file, finds all that contain the word git
then prints each one out in turn:
new File( '/Users/tim_yates/.bash_profile' ).text.tokenize( '\n' ).findAll {
it.contains 'git'
}.each {
println it
}

tim_yates
- 167,322
- 27
- 342
- 338
-
This is exactly what I wanted :) – Espen Schulstad Mar 01 '11 at 12:07
-
Obviously, if the files are massive, you'll want to scan them on a line-by-line basis with `File.eachLine` rather than the `File.text.tokenize` code above, which loads the whole file into RAM. Good luck and have fun! – tim_yates Mar 01 '11 at 12:17
-
Blogged about what I used it for : http://schulstad.blogspot.com/2011/03/logs-use-groovygrep-to-find-trends-in.html – Espen Schulstad Mar 02 '11 at 18:02
-
I would suggest that you replace .tokenize( '\n' ) with .readLines(). That would be cleaner and more system-independent. – Big Ed Dec 14 '15 at 20:39
-
Good idea. That method wasn't in groovy until 6 months after this answer – tim_yates Dec 14 '15 at 21:11