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



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

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

在外壳中,我可以做到:

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

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

任何帮助将不胜感激:)

假设您遇到的困难是 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 一起运行。

或者,如果您遇到目标系统使用dash,zsh,ksh或其他任何东西的情况,您也可以在shell中明确表示您希望ansible使用:

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

谢谢你的帮助,马修·丹尼尔。效果很好。

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

- 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 }}

最新更新