Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'ls -l' in groovy

Tags:

unix

groovy

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.

like image 249
Srinath Avatar asked Jun 21 '10 11:06

Srinath


People also ask

How do I search for files in groovy?

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).

How do I run a Linux command in groovy?

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.


3 Answers

"ls -l".execute().text

Should do it

like image 119
Bella Avatar answered Nov 23 '22 17:11

Bella


def list = 'ls -l'.execute().text
list.eachLine{
    // code goes here
}
like image 20
Michael Borgwardt Avatar answered Nov 23 '22 18:11

Michael Borgwardt


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.

like image 32
slim Avatar answered Nov 23 '22 18:11

slim