Search code examples
gitgrailsgroovy

Trim the paths from git diff result in Groovyscript


I am trying to trim the paths from git diff result. Here is what I have tried :

def ti = "git -C C:\\PIE\\src\\repo diff --name-only".execute()
String directory =ti.text
File  file= new File(directory)

 def newlines = []
    file.toString().eachLine {String line ->
    if(line.contains("src")){

        line = line.replace("/src","")
    }
    newlines<<line

    }
    println newlines
    

The output from gif diff for example is like :

a/b/c/src/ping.java
d/e/f/src/vim.java
g/h/j/src/key.java

I would like to trim each line in the file currentDir as :

a/b/c
d/e/f
g/h/j

Solution

  • If you want to remove the /src portion and all that follows it, you could do this:

    line = line.replaceAll("/src.*","") 
    

    instead of what you have:

    line = line.replace("/src","")