groovy - grep number of occurrences a string exists in a bunch of files -
i want count number of times string occurs in text files within folder , sub folders.
the command doing using grep on linux this
grep string * | wc -l
any ideas how using groovy instead?
thanks!
try:
assert 2 == ['a','b','c','a'].grep ( ~/a+/ ).size()
where ['a','b','c','a']
readlines()
file need process or file collection.
it works on file object:
def f = file.createtempfile('111','222') f.deleteonexit() f.text = "a\na\nb\nc" assert 2 == f.grep(~/a+/).size()
an sample solution:
import groovy.io.filetype def parent = file.createtempdir() parent.deleteonexit() def f1 = file.createtempfile('111','111', parent) f1.deleteonexit() def f2 = file.createtempfile('222','222', parent) f2.deleteonexit() def f3 = file.createtempfile('222','222', parent) f3.deleteonexit() f1.text = 'aa\naa\nbb' f2.text = 'cc\nbb\nbb' f3.text = 'cc\ncc\naa\naa' def files = [] parent.eachfilerecurse (filetype.files) { file -> files << file } assert 4 == files.collect { f -> f.grep(~/a+/).size() }.sum()
groovy count
No comments:
Post a Comment