Save the base name of each path in a list to a new list

Viewed 330

I have a list of paths which I want to transform to a list of file names in a new variable, i.e. from this:

paths:
- a/b/c/d.txt
- e/f/g/h.txt

To this:

filenames:
- d.txt
- h.txt

How do I make this debug print into a set_fact directive with a new variable?

- name: "Show base name, but how to save the list?"
  debug: msg={{ item | basename }}
  loop: "{{ paths }}"

I can use map(regex_replace), but I'm looking for a less hacky way to achieve this. Thanks!

1 Answers

Map the filter basename. For example

    - set_fact:
        files: "{{ paths|map('basename')|list }}"
    - debug:
        var: files

give

  files:
  - d.txt
  - h.txt
Related