我可以在所有名为的目录中运行命令_QWE
:
find . -name '_QWE' -type d -execdir touch {}/1234.txt \;
但是,我需要-execdir rename 's!^\./(\d+ -)\s(\d+\.)!$1!' {} \;
在 的所有直接子目录中运行_QWE
来重命名_QWE
.
我的意思是假设我有一个像这样的目录结构:
├── folder_1
│ └── _QWE
│ ├── Course 1
│ │ ├── 1 - Introduction
│ │ ├── 2 - 1. Basics of Course 1
│ │ ├── 3 - 2. Conclusion of Course 1
│ ├── Course 2
│ │ ├── 1 - Introduction
│ │ ├── 2 - 1. Basics of Course 2
│ │ ├── 3 - 2. Conclusion of Course 2
├── folder_2
│ └── folder_3
│ └── _QWE
│ ├── Course X1
│ │ ├── 1 - Introduction
│ │ ├── 2 - 1. Basics of Course X1
│ │ ├── 3 - 2. Conclusion of Course X1
│ ├── Course X2
│ │ ├── 1 - Introduction
│ │ ├── 2 - 1. Basics of Course X2
│ │ ├── 3 - 2. Conclusion of Course X2
这里我想重命名:
1 - Introduction
2 - 1. Basics of Course 1
3 - 2. Conclusion of Course 1
1 - Introduction
2 - 1. Basics of Course 2
3 - 2. Conclusion of Course 2
1 - Introduction
2 - 1. Basics of Course X1
3 - 2. Conclusion of Course X1
1 - Introduction
2 - 1. Basics of Course X2
3 - 2. Conclusion of Course X2
例如,此处3 - 2. Conclusion of Course X2
将重命名为3 - Conclusion of Course X2
.这就是作用's!^\./(\d+ -)\s(\d+\.)!$1!'
。
需要明确的是,3 - 2. Conclusion of Course X2
是目录名而不是文件名。
我怎样才能做到这一点?
更新1:
我可以使用以下方法获取路径:
for dir in $(find . -name '_QWE' -type d)/*/ ; do echo $dir ; done
或者,
for dir in $(find . -name '_QWE' -type d)/*/ ; do (cd "$dir"; pwd); done
但,
for dir in $(find . -name '_QWE' -type d)/*/*/ ; do rename 's!^\./(\d+ -)\s(\d+\.)!$1!' $dir ; done
没有产生任何输出。
答案1
您可以使用-path
修饰符来挑选紧邻匹配目录下的目录:
find . -depth -type d -path '*/_QWE/*/*' ! -path '*/_QWE/*/*/*' -exec rename 's!(/\d+)\s+-\s+\d+\.\s+([^/]*)$!$1 $2!' {} +
我稍微修改了您的 RE,将其锚定到匹配路径的文件名部分。 (对于此处使用的 PCRE 表达式,\s+
匹配一个或多个空白字符;\d+
匹配一个或多个数字;[^/]*
匹配一串零个或多个字符除了 /
.)
使用您的示例目录树,以下是使用时的相应输出rename -n
:
./folder_1/_QWE/Course 1/2 - 1. Basics of Course 1 renamed as ./folder_1/_QWE/Course 1/2 Basics of Course 1
./folder_1/_QWE/Course 1/3 - 2. Conclusion of Course 1 renamed as ./folder_1/_QWE/Course 1/3 Conclusion of Course 1
./folder_1/_QWE/Course 2/2 - 1. Basics of Course 1 renamed as ./folder_1/_QWE/Course 2/2 Basics of Course 1
./folder_1/_QWE/Course 2/3 - 2. Conclusion of Course 1 renamed as ./folder_1/_QWE/Course 2/3 Conclusion of Course 1
./folder_2/folder_3/_QWE/Course X1/2 - 1. Basics of Course 1 renamed as ./folder_2/folder_3/_QWE/Course X1/2 Basics of Course 1
./folder_2/folder_3/_QWE/Course X1/3 - 2. Conclusion of Course 1 renamed as ./folder_2/folder_3/_QWE/Course X1/3 Conclusion of Course 1
./folder_2/folder_3/_QWE/Course X2/2 - 1. Basics of Course 1 renamed as ./folder_2/folder_3/_QWE/Course X2/2 Basics of Course 1
./folder_2/folder_3/_QWE/Course X2/3 - 2. Conclusion of Course 1 renamed as ./folder_2/folder_3/_QWE/Course X2/3 Conclusion of Course 1
folder_4
为了进行测试,我还在 a 下但不在 a 目录下添加了一组使用相同名称的示例目录_QWE
。正如预期的那样,这些被正确地忽略了。