希望在重命名所有文件时扁平化目录(具有重复的子文件名),保留重复项或使用递增的数字附加所有文件名(递增 # + 名称是首选,但不是必需的)。这需要在 MacOS 上运行 - 将 bash 更新到 5.0.11。这是多步骤过程的一部分(递归解压缩、压平同时保留重复项、pdftotxt、grep for strings > txt 文件),但这是我在几个小时的搜索/测试后无法弄清楚的部分。
例子:
Dir1
Folder A
- file1.*
- File2.*
Folder B
- file1.*
- File2.*
- file3.*
Folder C
- File1.*
Desired output:
Dir1
- 1-file1.*
- 2-File2.*
- 3-file1.*
- 4-File2.*
- 5-file3.*
- 6-File1.*
有什么帮助吗?
答案1
作为一个两步过程:
单层
从...开始
.
├── a
│ ├── file1.pdf
│ ├── file1.txt
│ ├── file2.pdf
│ └── file2.txt
└── b
├── file1.pdf
└── file1.txt
1) 将文件移动到以其根名称命名的目录中:
├── a
│ ├── file1
│ │ ├── file1.pdf
│ │ └── file1.txt
│ └── file2
│ ├── file2.pdf
│ └── file2.txt
└─ b
└── file1
├── file1.pdf
└── file1.txt
2)迭代这些子目录,同时增加索引并移动/重命名文件
├── 1-file1.pdf
├── 1-file1.txt
├── 2-file2.pdf
├── 2-file2.txt
├── 3-file1.pdf
└── 3-file1.txt
代码(对于bash
)
# To be run with your Dir1 as the top directory.
tree .
for f in */* # iterate files in directories
do
dir="${f%.*}" # same with dropped extension
mkdir -p "$dir"
mv "$f" "$dir"
done
tree .
i=0
for d in */*/ # iterate subdirectories create above
do
(( ++i ))
for f in "$d"/*
do
mv "$f" $i-${f##*/} # drop path components and prefix with index
done
done
rmdir */*/ */
tree .
(您当然可以删除对 的调用tree
)。
多层次
从...开始:
.
├── a
│ ├── file1.pdf
│ ├── file1.txt
│ ├── file2.pdf
│ └── file2.txt
└── b
├── c
│ ├── file1.pdf
│ └── file1.txt
├── file1.pdf
└── file1.txt
中间步骤将给出:
.
├── a
│ ├── file1
│ │ ├── file1.pdf
│ │ └── file1.txt
│ └── file2
│ ├── file2.pdf
│ └── file2.txt
└── b
├── c
│ └── file1
│ ├── file1.pdf
│ └── file1.txt
└── file1
├── file1.pdf
└── file1.txt
最终是:
├── 1-file1.pdf
├── 1-file1.txt
├── 2-file2.pdf
├── 2-file2.txt
├── 3-file1.pdf
├── 3-file1.txt
├── 4-file1.pdf
└── 4-file1.txt
完整代码:
shopt -s extglob
shopt -s globstar
shopt -s nullglob
tree .
dirs=( */ )
for f in **/*.*
do
dir="${f%.*}"
mkdir -p "$dir"
mv "$f" "$dir"
done
tree .
i=0
for d in **/
do
files=("$d"/*.*)
[[ ${#files[@]} -eq 0 ]] && continue
(( ++i ))
for f in "${files[@]}"
do
mv -v "$f" $i-${f##*/}
done
done
rm -r */
tree .
此代码假设所有文件的名称(扩展名)中都有一个点,而目录则没有。