在包含具有不同扩展名(*.rules
和*.rules.yml
)的文件的文件夹中,我需要根据特定条件更改文件扩展名:
*.rules
=> *.rules.yml
或*.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
有什么想法可以做同样的事情吗?
任何帮助将不胜感激:)
答案 0 :(得分: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或其他内容,则也可以在希望使用的shell中明确显示它:
tasks:
- shell: echo "hello from bash"
args:
executable: /bin/bash
答案 1 :(得分: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 }}