提取不带扩展名的文件名-Ansible [英] Extract file names without extension - Ansible

查看:108
本文介绍了提取不带扩展名的文件名-Ansible的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ansible 中有一个 variable 文件,如下所示

I have a variable file in ansible like below

check:
       - file1.tar.gz
       - file2.tar.gz

tasks 中进行迭代时,我正在使用 {{item}}

while iterating it in tasks i am using {{item}}

with_items:-"{{check}}"

是否有一种在迭代时提取文件名而无需扩展名的方法?即我需要 file1.tar.gz 中的 file1 file2.tar.gz

Is there a way to extract the filenames without extension while iterating? i.e i need file1 from file1.tar.gz and file2 from file2.tar.gz

推荐答案

Ansible具有

Ansible has as splitext filter but unfortunately it only splits the extension after the last dot.

可靠地满足您的要求IMO的唯一解决方案是使用

The only solution to reliably achieve your requirement IMO is to extract the characters before the first dot using either the split() python method available on string objects or the regex_replace filter

对于您当前的需求,正则表达式解决方案有些过高.同时,它非常灵活,因为您可以轻松地使其适应更复杂的情况(在名称中匹配语义版本,查找特定模式).而且,由于它是一个过滤器(相对于 .split()的python本地方法),您可以使用它:

The regexp solution is a bit of an overkill for your current requirement. Meanwhile it is very flexible as you can easily adapt it to more complex situations (matching a semantic version in the name, look for a particular pattern). Moreover, since it is a filter (vs a python native method for .split()), you can either use it:

以下是以下剧本中每种解决方案的示例:

Here is an example for each solution in the below playbook:

---
- name: Extract file name without extension(s)
  hosts: localhost
  gather_facts: false

  vars:
    check:
      - file1.tar
      - file2.tar.gz
      - file3.tar.bz2.back
      - a_weird_file.name.with.too.many.dots

    file_regex: >-
      ^([^\.]*).*

  tasks:
    - name: use the split() function
      debug:
        msg: >-
          {{ item.split('.') | first }}
      loop: "{{ check }}"

    - name: Apply regex filter while looping
      debug:
        msg: >-
          {{ item | regex_replace(file_regex, '\1') }}
      loop: "{{ check }}"

    - name: Apply regex filter on list before loop
      debug:
        var: item
      loop: >-
        {{ check | map('regex_replace', file_regex, '\1') | list }}

这是结果.

注意:就我所知,我使用了 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆