如何在执行 build.gradle 之前使用 shell 脚本查找和替换行

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

我有一个 build.gradle 文件,通常在 windows 环境中执行;但是当在 Linux 环境中签出同一个文件时,某些行中提到的批处理文件会发生冲突,因此我们试图将构建失败的确切行替换为使它工作,在结帐完成后使用 shell 脚本。

build.gradle 文件

......
......
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']
    }
}
.....
.....

我想在执行构建之前实现以下目标;在源代码检出到本地工作区后。

task exportBatch中,要使用的行是

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

而不是

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

和 在task importBatch中,要使用的行

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

而不是

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

我们厌倦了根据行号更改行,但是当行号发生更改时,我们的方法失败了。

使用sed你可以试试

$ 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/,/}/ - exportBatch}

之间的匹配

s|commandLine =.*|commandLine 'sh', './export.sh'| - 在上面的匹配中,将内容为 commandLine =.* 的行替换为 commandLine 'sh', './export.sh' 注意 使用了双引号。

| - 管道被用作分隔符,但任何未出现在数据中的符号都可以用作分隔符。由于您的数据有 /,无法使用默认的 sed 分隔符,因为它会发生冲突并导致错误。

代码的第二部分重复相同的条件以处理第二次替换。