[英]ansible regexp for replace space quotes or comment
我有一個包含多行的文件。 其中一行可能如下所示:
item = 1000 or item = "1000" or item='1000' #with comment same line
or item = "1000'
或有關等號周圍空格的所有可能組合,或帶有單引號或雙引號或不帶引號,或者同樣,在同一行上有或沒有注釋。
簡而言之,我只需要獲取數字並使用 set fact 設置一個變量。 這件事快把我逼瘋了。
對不起,但我沒有把我所做的所有嘗試都放在一起,因為它們太多了。
myfile.conf:
start = 'before'
stop=after
item =100 #changed
bool= "yes"
class = 'first"
author = "Scott"
or item = 1000 or item = "1000" or item='1000' #blalala or item = "1000'
如上所述。
這是放棄前的最后一次嘗試:
- name: QUERY- read the myfile.conf
ansible.builtin.shell: cat "{{ './myfile.conf' }}"
register: resultline
- name: regex
ansible.builtin.set_fact:
mynumber: |-
{{
resultline.stdout |
regex_search("^item *=*.*", multiline=True) |
regex_replace(".*=*['\"](.*)['\"]*$", '\1')
}}
而且,當然,這行不通......
Expected result is:
mynumber = 1000
- command: cat myfile.conf
register: resultline
問: “在以item
開頭的行的=
之后帶有數字的 var mynumber
。”
A:讀取文件
conf_list:
- ' start = ''before'''
- ' stop=after '
- ' item =100 '
- ' bool= "yes"'
- ' class = "first"'
- ' author = "Scott"'
刪除評論並創建列表
conf_dict: "{{ conf_list|
map('regex_replace', '=', ': ')|
join('\n')|
from_yaml }}"
給
conf_dict:
author: Scott
bool: 'yes'
class: first
item: 100
start: before
stop: after
將 '=' 替換為 ': ' 並創建字典
my_number: "{{ conf_dict.item }}"
給
my_number: '100'
設置變量
- debug:
var: my_number|int + 1
給
my_number|int + 1: '101'
"{{ }}"
的計算結果始終是一個字符串。 您可以將其轉換為 integer。例如,
- debug: var: my_number|int + 1
給
my_number|int + 1: '101'
筆記
- hosts: localhost vars: conf_list: "{{ resultline.stdout_lines| map('regex_replace', conf_regex, conf_replace)| list }}" conf_regex: '^(.*)#.*$' conf_replace: '\1' conf_dict: "{{ conf_list| map('regex_replace', '=', ': ')| join('\n')| from_yaml }}" my_number: "{{ conf_dict.item }}" tasks: - command: cat myfile.conf register: resultline - debug: var: my_number - debug: var: my_number|int + 1
- debug: var: conf_dict.item|type_debug
給
conf_dict.item|type_debug: int
您可以在不進行轉換的情況下將其用於算術運算。 例如,
- debug: var: conf_dict.item + 1
給
conf_dict.item + 1: '101'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.