簡體   English   中英

如何使用 groovy 腳本查找和替換字符串

[英]How to find and replace string using groovy script

我需要從文件中搜索一些文本並使用 Groovy 腳本替換為其他字符串。 我在下面解釋我的文件。

測試.yml:

devices:
  test-server:
    type: test1
    os: test
    tacacs:
      username: admin
    passwords:
      tacacs: admin
    connections:
      defaults:
        class: unicon.Unicon
      cli:
        protocol: ssh
        ip: 1.1.1.1
        port: 2024
      rest:
        protocol: http
        ip: 1.1.1.1
        port: 8080
        username: admin
        password: admin
  RFS1:
    type: test
    os: test
    tacacs:
      username: admin
    passwords:
      tacacs: admin
    connections:
      defaults:
        class: unicon.Unicon
      cli:
        protocol: ssh
        ip: 1.1.1.1
        port: 2024
      rest:
        protocol: http
        ip: 4.4.4.4
        port: 8080
        username: admin
        password: admin
  RFS2:
    type: test
    os: test
    tacacs:
      username: admin
    passwords:
      tacacs: admin
    connections:
      defaults:
        class: unicon.Unicon
      cli:
        protocol: ssh
        ip: 1.1.1.1
        port: 2024
      rest:
        protocol: http
        ip: 6.6.6.6
        port: 8080
        username: admin
        password: admin

Here I need to search the IP which is under devices:/test-server:/connections:/cli:/ip: 1.1.1.1 with some new charcter like ip:10.10.10.10 using groovy script. 我正在使用下面的代碼。

def myFile = new File("test.yml") 
def fileText = myFile.text
fileText = (fileText =~ /ip:1.1.1.1/).replaceFirst("ip:10.10.10.10")
myFile.write(fileText)

在這里,我的問題是它在ip:1.1.1.1存在的整個文件中替換所需的字符串,但我需要在devices:/test-server:/connections:/cli:/ip: 1.1.1.1下替換。 請幫我解決這個問題。

更好的方法是簡單地進行 YAML 解析,操作 object,然后保存回文件。

這是使用 Jackson 的示例:

@Grab(group='com.fasterxml.jackson.dataformat', 
      module='jackson-dataformat-yaml', 
      version='2.12.2')

def myFile = new File("test.yml")
def om = new com.fasterxml.jackson.databind.ObjectMapper(
             new com.fasterxml.jackson.dataformat.yaml.YAMLFactory());
def value = om.readValue(myFile, Map)
value['devices']['test-server']['connections']['cli']['ip'] = '10.10.10.10'

這將替換內存中 object 中的值。 然后,您可以將其保存回文件,例如:

om.writeValue(myFile, value)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM