Sorting list in ansible in natural alphanumeric order

Viewed 388

Is there a way to sort list in Ansible / Jinja in natural way ?

For example this is the list

test
test123
test12
test5
test1234test
test22te

And I need it to take in account the numbers as whole not as individual so test12 is under test5 and so on...

2 Answers

Create a list with an attribute index of type integer, e.g.

    - set_fact:
        l2: "{{ l2|default([]) +
                [{'index': (_index|length > 0)|ternary(_index|int, 0),
                  'name': item}] }}"
      loop: "{{ l1 }}"
      vars:
        _regex: '^test(\d*)\D*$'
        _replace: '\1'
        _index: "{{ item|regex_replace(_regex, _replace) }}"
    - debug:
        msg: "{{ l2|sort(attribute='index')|
                    map(attribute='name')|
                    list }}"

gives

  msg:
  - test
  - test5
  - test12
  - test22te
  - test123
  - test1234test
Related