将具有特定文件扩展名的多个文件更改为文件夹中的另一个扩展

问题描述 投票:0回答:2

在包含具有不同扩展名(*.rules*.rules.yml)的文件的文件夹中,我需要根据特定条件更改文件扩展名:

  1. *.rules => *.rules.yml,或
  2. *.rules.yml => *.rules

在shell中,我可以这样做:

Case # 1
for file in ./*.rules; do mv "$file" "${file%.*}.rules.yml" ; done 
# from *.rules to *.rules.yml


Case # 2
for file in ./*.rules.yml ; do mv "$file" "${file%.*.*}.rules" ; done 
# from *.rules.yml to *.rules

有什么想法可以做同样的事吗?

任何帮助将不胜感激 :)

ansible
2个回答
2
投票

假设您遇到的困难是使用YAML引用,您可能会遇到“管道文字”更好的运气:

  tasks:
  - shell: |
      for i in *.rules; do
        /bin/mv -iv "$i" "`basename "$i" .rules`.rules.yml"
      done
  - shell: |
      for i in *.rules.yml; do
        /bin/mv -v "$i" "`basename "$i" .rules.yml`.rules"
      done

人们还会注意到我使用了更传统的basename而不是尝试做“狡猾​​的”变量扩展技巧,因为它应该运行任何posix shell。

或者,如果您遇到目标系统使用破折号,zsh或ksh等等,您也可以在希望ansible使用的shell中显式:

tasks:
- shell: echo "hello from bash"
  args:
    executable: /bin/bash

0
投票

谢谢你的帮助,Matthew L Daniel。它运作得很好。

最终工作解决方案将作为参考:

- name: Run in local to replace suffix in a folder
  hosts: 127.0.0.1 
  connection: local

  vars:
    - tmpRulePath: "rules"
    - version: "18.06" # change the version here to change the suffix from rules/rules.yml to rules.yml/rules
    - validSuffix: "rules.yml"
    - invalidSuffix: "rules"

  tasks:
  - name: Prepare the testing resources
    shell: mkdir -p {{ tmpRulePath }}; cd {{ tmpRulePath }}; touch 1.rules 2.rules 3.rules.yml 4.rules.yml; cd -; ls {{ tmpRulePath }};
    register: result

  - debug:
      msg: "{{ result.stdout_lines }}"

  - name: Check whether it's old or not
    shell: if [ {{ version }} \< '18.06' ]; then echo 'true'; else echo 'false'; fi
    register: result

  - debug:
      msg: "Is {{ version }} less than 18.06 {{ result.stdout }}"

  - name: Update validSuffix and invalidSuffix
    set_fact:
      validSuffix="rules"
      invalidSuffix="rules.yml"
    when: result.stdout == "true"

  - debug:
      msg: "validSuffix is {{ validSuffix }} while invalidSuffix {{ invalidSuffix }}"

  - name: Replace the invalid suffix with valid
    shell: |
      cd {{ tmpRulePath }};
      for i in *.{{ invalidSuffix }}; do
        /bin/mv -v "$i" "`basename "$i" .{{ invalidSuffix }}`.{{ validSuffix }}"
      done

  - name: Check the latest files
    shell: ls {{ tmpRulePath }}
    register: result

  - debug:
      msg: "{{ result.stdout_lines }}"

  - name: Clean up
    shell: rm -rf {{ tmpRulePath }}
© www.soinside.com 2019 - 2024. All rights reserved.