Home > Software design >  How to find and replace lines in the build.gradle before executing it, using shell script
How to find and replace lines in the build.gradle before executing it, using shell script

Time:11-19

I have a build.gradle file which usually been executed in a windows environment; but when the same file is checked out in a Linux environment, the batch file mentioned in some of the lines gets conflicted, so what we were trying is to replace the exact lines where the build gets failed, to the lines that makes it work, using a shell script after the checkout gets completed.

build.gradle file

......
......
task exportBatch(type:Exec) {
    doFirst {
        println "Exporting batch..."
        commandLine = ['cmd', '/C', 'start', 'export.bat']
    }
}
task importBatch(type:Exec) {
    doFirst {
        println "Importing batch..."
        commandLine = ['cmd', '/C', 'start', 'import.bat']
    }
}
.....
.....

I would like to achieve the following before executing the build; after the source codes gets checked out to local workspace.

In task exportBatch, the line to be used is

commandLine 'sh', './export.sh'

instead of

commandLine = ['cmd', '/C', 'start', 'export.bat']

and in task importBatch, the line to be used

commandLine 'sh', './import.sh'

instead of

commandLine = ['cmd', '/C', 'start', 'import.bat']

We tired changing the line based on the line number, but when there is a change of line numbers our method fails.

CodePudding user response:

Using sed you can try

$ sed "/exportBatch/,/}/ {s|commandLine =.*|commandLine 'sh', './export.sh'|}; /importBatch/,/}/ {s|commandLine =.*|commandLine 'sh', './import.sh'|}" input_file
......
......
task exportBatch(type:Exec) {
    doFirst {
        println Exporting batch...
        commandLine 'sh', './export.sh'
    }
}
task importBatch(type:Exec) {
    doFirst {
        println Importing batch...
        commandLine 'sh', './import.sh'
    }
}
.....
.....

/exportBatch/,/}/ - Match between exportBatch and }

s|commandLine =.*|commandLine 'sh', './export.sh'| - Within the match above, substitute the line with content commandLine =.* with commandLine 'sh', './export.sh' NOTE Double quotation was used.

| - The pipe was used as a delimiter but any symbol that does not appear in the data can be used as the delimiter. As your data had /, the default sed delimiter could not be used as it would conflict and cause an error.

The same conditions are repeated in the second part of the code to handle the second substitution.

  • Related