簡體   English   中英

我想替換與特定模式/行相關的單詞

[英]I want to replace a word which is associated with a particular pattern/line

假設一個文件(socket.cfg)具有以下內容

socket1:a:1.2.3.4:wso,ws1,ws2
socket2:b:2.5.6.7:ws3,ws5,ws7

現在我只想更改“socket1”包含在行中的 IP 並且 rest 應該保持不變。 給我的數據只有 socket1 和 IP 需要更改。

我確實嘗試過 lineinfile 並替換模塊,但整個模式發生了變化。 請幫幫我。 它類似於 sed 命令,例如sed /socket1/<Ip_pattern>/<replacing_IP>所以這轉到 socket1 行,只選擇 ZA12A3079E14CED46E69BA52B8A90B。 我想要這樣的東西。

這里是你需要的,

- name: replace the ip address
  lineinfile:
    path: /path/to/socket.cfg
    regexp: ^(socket1)(.*)(\d+.\d+.\d+.\d+)(.*)
    line: \g<1>\g<2>{{ inventory_hostname }}\g<4>
    backrefs: yes

注意:我在替換內容時使用了正則表達式組。

我已將 IP 替換為inventory_hostname ,在我的例子中是localhost,您可以將其更新為您想要的任何內容。

輸入:

socket1:b:1.2.3.4:ws3,ws5,ws7
socket2:b:2.5.6.7:ws3,ws5,ws7

Output:

socket1:b:localhost:ws3,ws5,ws7
socket2:b:2.5.6.7:ws3,ws5,ws7

暫無
暫無

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

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