我可能在这里过头了。我正在尝试创建一个bash脚本来识别以5位数字开头的文件,检查该匹配文件(或文件组)是否存在目录,并将文件移动到目录中。如果目录不存在,我想创建它,然后移动文件。
这是我到目前为止所获得的剧本,但实际上它根本不是很远。
#!/bin/bash
files=($(find . -type f | grep -E "[0-9]{5}" -o))
directories=($(find . -type d))
for i in ${files[*]}
do
printf "▸ ▸ pdf file found: %s\n" $i
done
for d in ${directories[*]}
do
printf "▸ ▸ directory found: %s\n" $d
done
NewDir=(`echo ${files[@]} ${directories[@]} | tr ' ' '\n' | sort | uniq -u `)
for nd in ${NewDir[*]}
do
printf "mkdir for: %s\n" $nd
done
需要排序的目录示例如下所示:
476B Oct 19 14:43 .
544B Oct 21 10:36 ..
68B Sep 17 08:14 12345/
68B Sep 17 08:14 12735/
0B Sep 17 08:14 29375.pdf
0B Sep 17 08:14 29375a.pdf
0B Sep 17 08:14 29375-1.pdf
0B Sep 17 08:14 32952.pdf
0B Sep 17 08:14 39472.pdf
68B Sep 17 08:14 59723/
0B Sep 17 08:14 97132.pdf
273B Oct 19 14:43 sort.sh
因此,关于这个例子,我想识别以29375开头的文件并为它们创建一个目录,然后将它们移动到该目录中。
这是我遇到麻烦,将找到的文件与存在的目录进行比较。 NewDir数组是我在尝试搜索解决方案时正在进行的测试。
感谢先进的反馈/帮助。
答案 0 :(得分:1)
如果我正确理解你的问题,那就完成了工作,不需要使用数组:
for dir in $(find -E . -type f -regex ".*/[[:digit:]]{5}.*" \
| sed -E 's@\./([0-9]{5}).*@\1@' | sort -u) ; do
if [ ! -d "$dir" ] ; then
mkdir "$dir"
fi
if [ ! -d "$dir" ] ; then
continue
fi
find -E . -type f -regex ".*/$dir.*" -exec mv \{\} $dir \;
done
根据目录的数量,您可能需要将此转换为使用消耗while
输出的find -E . -type f -regex ".*/[[:digit:]]{5}.*" | sed -E 's@\./([0-9]{5}).*@\1@' | sort -u
循环,因为其当前形式后者可能超过可接受的长度。
编辑:请注意-regex
实际上是一个gnu查找扩展名,所以只有当GNU find是在PATH上找到的第一个find
时它才会起作用