laxris
laxris

Reputation: 481

Split a text to words with regex_findall

what I am trying to do is to split a text into words. I do not want to split it only by space but from other delimiters such as "=", and I do not want to split when there is a dot (.) because I want to keep IPs as a whole word. An example of a file that contains the words I want to split is

> cat myconfig.xtx
key1=192.168.0.1
key2 = 192.168.0.2
key3="192.168.0.3"
key4 = "192.168.0.4"

from the terminal, I am running something like

grep -oE '(\w|\.)+' mycongig.txt

and it is running as expected, even if I do not fully understand why :) But when I am trying to use it in jinja2 template with regex_findall I can not make it work.

I have tried something like this in ansible (among several other tries)

- name: Split words
  debug:
    msg: "{{ lookup('file', item) | regex_findall('(\\w|\\.)+') }}"
  loop: "{{ files }}"

Any ideas? Thank you in advance

Upvotes: 2

Views: 264

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68144

Map regex_findall, e.g.

    - debug:
        msg: "{{ lookup('file', 'mycongig.txt').splitlines()|
                 map('regex_findall', '[\\w\\.]+')|
                 list }}"

gives

  msg:
  - - key1
    - 192.168.0.1
  - - key2
    - 192.168.0.2
  - - key3
    - 192.168.0.3
  - - key4
    - 192.168.0.4

Upvotes: 2

Related Questions