Home > front end >  How to search and match pattern to get a value in ansible
How to search and match pattern to get a value in ansible

Time:12-31

My variable info has below value. (Actual case has huge data).

I am trying to search for specific word XYZ_data_001 and get the size information, which is after the pattern physical disk,

XYZ_data_001         file system device, special, dsync off, directio on, physical disk, 16384.00 MB, Free: 0.00 MB      2         0      6       0  8388607
XYZ_data_002         file system device, special, dsync off, directio on, physical disk, 16384.00 MB, Free: 0.00 MB      2         0     13       0  8388607

here is what is tried

    - name: Print size
      ansible.builtin.debug:
        msg: "{{ info | regex_search('XYZ_data_001(. )') | split('physical disk,') | last }}"

this will give me below output

ok: [testhost] => {
    "msg": " 16384.00 MB, Free: 0.00 MB      2         0      6       0  8388607 "
}

Thanks in advance

CodePudding user response:

You can use

{{ info | regex_search('XYZ_data_001\\b.*physical disk,\\s*(\\d[\\d.]*)', '\\1') }}

See the regex demo.

Details:

  • XYZ_data_001 - a XYZ_data_001 string
  • \b - a word boundary
  • .* - any text (any zero or more chars other than line break chars as many as possible)
  • physical disk, - a literal string
  • \s* - zero or more whitespaces
  • (\d[\d.]*) - Group 1 (\1): a digit and then zero or more digits or dots.
  • Related