How do I execute a command on a list of files?

Hi,

I’m new to gradle. So far I’ve followed the Getting Started section at gradle.org and an article in a magazine that is based on http://www.dpunkt.de/leseproben/4015/4_Einleitung.pdf (in German).

To expand on that I tried to create a small build script that runs a command for a list of files. Assuming I have a directory with text files (*.txt) I want to call “dos2unix” for each of them (a simplified version of what I want to do).

A build file to print all of the text files wasn’t that hard:

task all << {
    FileTree tree = fileTree('.').include('*.txt')
    tree.each {File file ->
        println file
    }
}

So all I need to do is basically replace “println” with “dos2unix”. What I found regarding the execution of arbitrary commands is something along those lines:

task dostounix(type: Exec) {
    executable "sh"
    args "-c", 'dos2unix "<filename>"'
}

But I fail to combine both pieces of code. Can I do something like this?

task all << {
    FileTree tree = fileTree('.').include('*.txt')
    tree.each {File file ->
        tasks.dostounix.execute(file)
    }
}

Any help would be greatly appreciated :slight_smile: Brack

There are two ways to trigger a commandline tool in gradle.

  1. The Exec task like you declared it in your example 2. the project.exec util method.

In your szenario I would recommend to use the project.exec method. Exec Task and exec method have the same api. In general calling the execute method on a task is not recommended/supported by gradle. I created a sample snippet for your usecase on github: https://gist.github.com/breskeby/7858657

cheers, René

Cool, thank you.

In the long run, for not so simple tasks as running dos2unix I’d like to execute the commands in parallel.