Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string to get all but the last element

Here is my playbook

---
- name: This is a hello-world example
  hosts: localhost
  vars:
    mystr: "I.To.Be.war"
  tasks:

    - name: Hi
      debug:
        msg: "{{ mystr.split('.') | first | trim }}"

Output:

I

The trim filter is to get rid of \r\n at the end of the variable incase it has.

However, I wish a generic solution that should print everything before the last element of the split delimiter, i.e.: ..

Expected output:

I.To.Be

Note: I do not want a solutions like "{{ mystr.split('.')[0][1][2] }}" as it is not generic in nature.

like image 735
Ashar Avatar asked Oct 23 '25 11:10

Ashar


2 Answers

  1. Apply the trim filter to every element of your list using the map filter
  2. Using python list slicing to get everything but the last
  3. Join the elements back
$ ansible localhost -m debug \
-a "msg={{ (mystr.split('.') | map('trim'))[:-1] | join('.') }}" \
-e "mystr=I.to.be.war"
localhost | SUCCESS => {
    "msg": "I.to.be"
}

Alternatively, you can use a regex to match the first part of the string

$ ansible localhost -m debug \
-a 'msg={{ mystr | regex_replace("^(.*)\\.[^.]*$", "\\1") }}' \
-e "mystr=I.to.be.war"
localhost | SUCCESS => {
    "msg": "I.to.be"
}
like image 192
Zeitounator Avatar answered Oct 25 '25 00:10

Zeitounator


Since your requirement seems to be about getting the name of a file without its extension, mind that there is a extra Jinja filter, splitext, purposed for that:

Where, the task

- debug:
    var: "'I.To.Be.war' | splitext | first | trim"

will give your expected

ok: [localhost] => 
  '''I.To.Be.war'' | splitext | first | trim': I.To.Be

While the filter splitext is actually returning a tuple, more convenient than a regular split:

ok: [localhost] => 
  '''I.To.Be.war'' | splitext | trim': ('I.To.Be', '.war')
like image 31
β.εηοιτ.βε Avatar answered Oct 25 '25 00:10

β.εηοιτ.βε



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!