- Groovy 2 Cookbook
- Andrey Adamovich Luciano Fiandesio
- 400字
- 2021-07-23 15:57:19
Using Groovy as a command-line text file editor
The groovy
command, which we introduced in the Executing Groovy code from the command line recipe, can also be used as a stream editor or text file filter. In this recipe, we will cover the -i
, -n
, and -p
parameters that can be used to leverage file editing and processing functionality.
How to do it...
Assume that you have a file, data.txt
, which contains five lines with numbers from 1
to 5
:
- To multiply each number by 2, you can use the following command:
groovy -n -e "println line.toLong() * 2" data.txt
- We can even omit the
println
method call if we pass additional the-p
parameter to the command:groovy -n -p -e "line.toLong() * 2" data.txt
- In both cases, Groovy will print the following output:
2 4 6 8 10
How it works...
Due to the fact that we are using the -n
option, the code in double quotes is applied to each line read from the datafile specified as the last parameter in the command line. The line variable is predefined by Groovy, and you can use it to access, filter, or modify the line's content.
There's more...
If you add the -i
option to the previous command, then it will actually modify the input file, with output values as follows:
groovy -i -n -p -e "line.toLong() * 2" data.txt
Adding a suffix .bak
to the -i
option will save the original input file data.txt
under data.txt.bak
:
groovy -i .bak -n -p -e "line.toLong() * 2" data.txt
You can use the -n
and -p
options to filter the input stream of other operating system commands. For example, if you want to filter the output of a directory listing command (dir
) to show only the *.jar
files, on Windows you can use the following command:
dir | groovy -n -e "if (line.contains('.jar')) println line"
Or on *nix-based operating systems, you can use the following command:
ls -la | groovy -n -e "if (line.contains('.jar')) println line"
Of course, the result of the previous commands can be easily achieved by more efficient operating system instructions. However, these examples are given to demonstrate that you can actually leverage the full power of the Groovy and Java programming languages to implement more complex processing rules.
See also
- Executing Groovy code from the command line
- Using Groovy to start a server on the command line
- 從零開始:數(shù)字圖像處理的編程基礎(chǔ)與應(yīng)用
- Arduino by Example
- Vue.js 3.x從入門到精通(視頻教學(xué)版)
- ASP.NET Core 2 and Vue.js
- Java游戲服務(wù)器架構(gòu)實(shí)戰(zhàn)
- Eclipse Plug-in Development:Beginner's Guide(Second Edition)
- Babylon.js Essentials
- Visual C#.NET Web應(yīng)用程序設(shè)計(jì)
- Principles of Strategic Data Science
- Continuous Delivery and DevOps:A Quickstart Guide Second Edition
- UML基礎(chǔ)與Rose建模實(shí)用教程(第三版)
- WCF技術(shù)剖析(卷1)
- 計(jì)算機(jī)應(yīng)用基礎(chǔ)案例教程(第二版)
- Java服務(wù)端研發(fā)知識圖譜
- iOS應(yīng)用逆向工程:分析與實(shí)戰(zhàn)