Notification texts go here Contact Us Buy Now!

Split string to get all but the last element

  • Ansible's regex_replace() filter:
mystr | regex_replace('\\.[^.]+$', '')
  • Using map filter, trim filter, and Python list slicing:
  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"
}
  • Using 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"
}
  • Using the splitext filter:
- debug:
    var: "'I.To.Be.war' | splitext | first | trim"
ok: [localhost] => 
  '''I.To.Be.war'' | splitext | first | trim': I.To.Be
  • Using regex_replace() filter to create a directory:
- name: "Create folder"
  ansible.builtin.file:
    path: '{{ sample_variable_name_from_group_vars_all | regex_replace("^(.*)\\.[^.]*$", "\\1") }}'
    state: directory

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.