Ansible regex_search/regex_findall [英] Ansible regex_search/regex_findall

查看:32
本文介绍了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秒

当没有时间时,它会返回如下一行:

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:

好的:[本地主机] => {"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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆