Ansible regex_search/regex_findall [英] Ansible regex_search/regex_findall
问题描述
我正在尝试解析返回这样的行的命令的输出(输出更多,但这是我要的行):
I'm trying to parse the output of a command that returned a line like this (there's more output, but this is the line that I'm after):
剩余时间:3分钟12秒
Remaining Time: 3 Minutes and 12 Seconds
当没有时间可用时,它会返回这样的一行:
And when there is no time left it returns a line like this:
剩余时间:0秒
我想提取分钟和秒,所以我可以将其输入到GNU date -d.首先,我尝试了这个:
I'd like to extract the amount of minutes and seconds, so I can feed it to GNU date -d. First I tried this:
- name: determine how much time we have left
set_fact:
time_left: "{{ cmd_output.stdout | regex_search(time_left_regex, '\\1', '\\2') | join(' ') }}"
vars:
time_left_regex: 'Remaining Time: ([0-9]+ Minutes) and ([0-9]+ Seconds)'
但是,这将无法处理没有时间的情况.因此,我尝试了以下方法:
But this does not handle the case when there is no time left. So I then tried something like this:
- name: determine how much time we have left
set_fact:
time_left: "{{ cmd_output.stdout | regex_findall(time_left_regex, '\\1') }}"
vars:
time_left_regex: 'Next Execution:.*([0-9]{1,2} (Minutes|Seconds))'
但这只会返回类似的内容:
But this only returns something like:
好:[localhost] => {"msg":剩余时间:[[u'2 Seconds',u'Seconds']]"}
ok: [localhost] => { "msg": "time left: [[u'2 Seconds', u'Seconds']]" }
我认为我走在正确的轨道上,但是我需要更好的正则表达式,所以也许有人可以在这里帮助我?提前非常感谢您.
I think I'm on the right track but I need a better regex, so maybe somebody can help me out here? Thank you so much in advance.
推荐答案
可以拆分字符串(行)并组合字典.例如
It's possible to split the string (line) and combine a dictionary. For example
- set_fact:
time_left: "{{ time_left|default({})|
combine({myline[item]: myline[item+1]}) }}"
loop: "{{ range(0, myline|length + 1, 3)|list }}"
vars:
myline: "{{ cmd_output.stdout.split(':').1.split()|reverse|list }}"
- debug:
var: time_left
用于各种命令输出
cmd_output.stdout: 'Remaining Time: 3 Minutes and 12 Seconds'
cmd_output.stdout: 'Remaining Time: 0 Seconds'
cmd_output.stdout: 'Remaining Time: 2 Days and 7 Hours and 3 Minutes and 12 Seconds'
分别给予
"time_left": {
"Minutes": "3",
"Seconds": "12"
}
"time_left": {
"Seconds": "0"
}
"time_left": {
"Days": "2",
"Hours": "7",
"Minutes": "3",
"Seconds": "12"
}
这篇关于Ansible regex_search/regex_findall的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!