Posted by tomwhite
on April 18, 2005 at 12:55 PM PDT
Bringing Perl-style one-liners to Java.
Perl is famous for its one-liners . By using the
-e command line switch you can execute the script supplied as an argument. But the real power comes when you use
-p (to process each line of a supplied file), and
-i (to modify the file in place). The classic example is to perform search and replace on a bunch of files . The following will replace all occurrences of
curious george with
perl -pi -e 's/curious george/the gruffalo/g' favourites.html
I was happy to learn recently that you can do the same with Groovy. Groovy supports the same set of command line arguments , but the script is obviously more Java-ish (the
=~ operator is a Groovy regex operator ):
groovy -pi -e "(line =~ 'curious george').replaceAll('the gruffalo')" favourites.html
OK, it's not quite as terse, but it's still a one-liner. (Actually, there is a bug in the latest version of Groovy, JSR 1, which prevents the
-i switch from functioning correctly. Hopefully it will be fixed soon. As a workaround you can call
groovy -pi.bak -e ... which has the same effect and in addition backs up the original file.)
More complicated examples provide a great way to learn more about Groovy features . This
prints the first and penultimate whitespace-separated columns from a text file, and shows off Groovy's Python-inspired slicing ability.
groovy -pe "line.split('\\s')[0, -2]" *
And this will find duplicate words:
groovy -ne "if (line =~ '\\b(\\w+)\\b\\s+\\b\\1\\b') println line" *
Do you have any Groovy one-liners?