I need to display name, size, date of files using ls -l
unix command in groovy .
How can we run ls -l
in groovy to view info ?
thanks in advance.
fileFind.groovy The above script will print out the name of any file it finds matching the provided string. If I pass $ to it without escaping the dollar sign, all files in the directory are returned. Using backslash to escape the dollar sign accomplishes what I want (only files with $ in their name).
Executing shell commands using Groovy is very easy. For example If you want to execute any unix/linux command using groovy that can be done using execute() method and to see the output of the executed command we can append text after it.
"ls -l".execute().text
Should do it
def list = 'ls -l'.execute().text
list.eachLine{
// code goes here
}
If you don't mind restricting yourself to the file properties that Java knows about, you can do this in a more portable, flexible, secure and efficient way using methods of the File class.
File dir = new File(".")
dir.eachFile { f ->
println "${f} ${f.size()} ${new Date(f.lastModified())}"
}
Check both the GroovyDocs and the JavaDocs for File to see all the ways you can filter files, and all the properties you have access to.
Of course you could have any code in that block, replacing println.
In the Perl world, we learned that invoking shell commands was usually to be avoided, when native Perl was an option. This is even more true in Groovy, I'd argue. Of course, you might have a special requirement, where you need the exact output 'ls -l' would produce.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With