【问题标题】:remove all files containing a certain name within a directory删除目录中包含特定名称的所有文件
【发布时间】:2015-08-21 18:05:25
【问题描述】:

我有以下目录,它有以下文件:

/tmp/test/file1.txt
/tmp/test/file1.txt.backup
/tmp/test/mywords.csv

如何使用file 模块仅删除file1* 文件?

【问题讨论】:

  • 我已更新我的答案以包含新的 fileglob 循环,它在单个任务中执行此操作。

标签: ansible


【解决方案1】:

edit:Ansible 2.0 现在已经发布,所以之前的答案应该可以工作,你现在也可以loop over fileglobs。请注意,这仅在您在本地运行 Ansible 时才有效:

- file:
    path: "{{item}}"
    state: absent
  with_fileglob:
    - /tmp/test/file*

原答案:

我目前无法找到一种方法来执行此操作而无需放入 shell,但是如果您可以放入 shell 以收集与模式匹配的文件列表并将其保存为变量,那么您可以循环带有 with_items 的文件模块

Ansible 2.0 将包含一个“查找”模块,可为您获取列表:http://docs.ansible.com/ansible/find_module.html

这里有几个任务应该在 ansible 2.0 中完成,但我没有安装它,所以我没有测试它,可能会错误地访问 find 模块的结果。

- find:
    paths: "/tmp/test"
    patterns: "file*"
  register: result

- file:
    path: "{{item.path}}" #correction code
    state: absent
  with_items: result.files

【讨论】:

  • 酷..谢谢。只需要等待2.0正式发布,然后我会使用它。
  • 第二种解决方案有效,但第一种(使用 fileglobs)不正确,因为 fileglobs 似乎只在本地文件系统上有效。请参阅github.com/ansible/ansible/issues/10115 了解更多信息。
  • 你说得对,卡洛斯。我已经更新了我的答案以表明这一点。
【解决方案2】:

你可以使用上面显示的 find + file 模块,但是在 ansible

ERROR: find is not a legal parameter in an Ansible task or handler

以下命令即可(您可以将 -regex 替换为 -name "files1*"):

- name: delete files
  shell: 'find /tmp/test/ -maxdepth 1 -type f -regex "/tmp/test/file1.*" -exec rm -rf {} \;'

【讨论】:

    【解决方案3】:

    所以我不在 linux 终端前,但如果你想确保只删除文件内容,你可以使用它。应该可以,但您可能需要对其进行调整。

    find . -name files1* -type f -exec basename {} \; | xargs rm
    

    【讨论】:

    • 我正在使用 ansible(IT 编排工具)。它们提供模块来在远程主机上执行某些操作。这些模块之一是文件模块。 docs.ansible.com/ansible/file_module.html。您如何使用该模块来删除文件。我想使用它,因为它是幂等的,而不是真正的 linux 命令。我有一个 linux 命令,它已经通过执行 -> rm name* 将其删除
    【解决方案4】:
    - hosts: srv-lnx
      gather_facts: no
    
      tasks:
        - shell: "find /var/tmp/collect -maxdepth 1 -type f | awk -F/ '{print $NF}'"
          register: result
    
        - debug: var=result
    
        - fetch: src=/var/tmp/collect/{{ item }} dest=/appl/collect/data flat=yes
          with_items: result.stdout_lines
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      • 2014-07-11
      • 1970-01-01
      • 2023-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多