【问题标题】:Replace the string in file using groovy使用groovy替换文件中的字符串
【发布时间】:2014-03-07 08:59:40
【问题描述】:

我有一个名为“silent.txt”的文件。该文件有如下一行

bop4InstallDir = myProps.cordys_install_dir + "/" + instanceName

我想把上面的文字替换成

bop4InstallDir = "/abc/xyz/pqr"

使用 groovy 脚本如何完成此操作? 请帮忙。

【问题讨论】:

    标签: grails groovy groovyshell


    【解决方案1】:

    以下代码有效:

    def file = new File("silent.txt")
    def fileText = file.replaceAll("bop4InstallDir\\ \\=\\ myProps.cordys_install_dir\\ \\+\\ \"\\/\"\\ \\+\\ instanceName", "bop4InstallDir\\ \\=\\ \"/opt/cordys/bop4/defaultInst1\"")
        file.write(fileText);
    

    【讨论】:

      【解决方案2】:

      silent.txt 是格式良好的属性文件吗?在这种情况下,您可以使用多种方式来访问它们,比愚蠢的替换更安全。

      groovy: How to access to properties file?ConfigSlurper

      【讨论】:

      • 它不是属性文件。它是一个 groovy 脚本。
      【解决方案3】:

      不是很优雅,但这应该可以。

      def file = new File("silent.txt")
      
      file.text = file.text.replace('bop4InstallDir = myProps.cordys_install_dir + "/" + instanceName', 
      'bop4InstallDir = "/abc/xyz/pqr"')
      

      【讨论】:

      • 它不工作。错误类似于“期望 EOF,发现 ')'@ 第 6 行第 34 列。'bop4InstallDir = "/abc/xyz/pqr"')"
      • 我认为你放错了引号。请按原样复制上面的代码,然后尝试。
      • 复制的代码无效。我和'/'、'+'之类的特殊字符有些关系......
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      相关资源
      最近更新 更多