【问题标题】:How to find and replace lines in the build.gradle before executing it, using shell script如何在执行之前查找和替换 build.gradle 中的行,使用 shell 脚本
【发布时间】:2021-12-29 13:43:20
【问题描述】:

我有一个 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中,要使用的行是

命令行 'sh', './export.sh'

而不是

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

和 在 task importBatch 中,要使用的行

命令行 'sh', './import.sh'

而不是

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

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

【问题讨论】:

    标签: bash shell sed


    【解决方案1】:

    使用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 分隔符,因为它会冲突并导致错误。

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

    【讨论】:

    • 感谢@HatLess;它解决了我的问题。如果你能解释你的答案会很有帮助。
    • 当然@Wolf 给我一点时间来输入它。
    猜你喜欢
    • 2012-06-07
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 2016-11-09
    • 2013-09-19
    相关资源
    最近更新 更多