场景:
随着 Locky 病毒的横行,我工作的计算机中心发现文件恢复的唯一方法是使用 Recuva 等工具,现在的问题是它将所有恢复的文件转储到一个目录中。我想将所有这些基于文件扩展名的文件移至类别中。所有 JPG 在一个中,所有 BMP 在另一个中......等等。我查看了 Stackoverflow 并根据各种其他问题和答复,我设法构建了一个小型 bash 脚本(提供了示例),它有点做到这一点,但需要很长时间才能完成,并且我想我的扩展搞砸了。
代码:
#!/bin/bash
path=$2 # Starting path to the directory of the junk files
var=0 # How many records were processed
SECONDS=0 # reset the clock so we can time the event
clear
echo "Searching $2 for file types and then moving all files into grouped folders."
# Only want to move Files from first level as Directories are ok were they are
for FILE in `find $2 -maxdepth 1 -type f`
do
# Split the EXT off for the directory name using AWK
DIR=$(awk -F. '{print $NF}' <<<"$FILE")
# DEBUG ONLY
# echo "Moving file: $FILE into directory $DIR"
# Make a directory in our path then Move that file into the directory
mkdir -p "$DIR"
mv "$FILE" "$DIR"
((var++))
done
echo "$var Files found and orginized in:"
echo "$(($diff / 3600)) hours, $((($diff / 60) % 60)) minutes and $(($diff % 60)) seconds."
问题:
如何在处理超过 500,000 个文件时提高效率?查找需要很长时间才能获取文件列表,并在循环中尝试创建目录(即使该路径已经存在)。如果可能的话,我希望更有效地处理循环的这两个特定方面。
最佳答案
任何 bash 脚本的瓶颈通常是您启动的外部进程的数量。在这种情况下,您可以认识到您要移动的大部分文件都具有 jpg
等常见后缀,从而大大减少对 mv
的调用次数等等。从这些开始。
for ext in jpg mp3; do
mkdir -p "$ext"
# For simplicity, I'll assume your mv command supports the -t option
find "$2" -maxdepth 1 -name "*.$ext" -exec mv -t "$ext" {} +
done
使用 -exec mv -t "$ext"{} +
意味着 find
将向每次调用 mv
传递尽可能多的文件>。对于每个扩展,这意味着一次调用find
和最少次数的mv
调用。
移动这些文件后,然后您就可以开始一次分析一个文件。
for f in "$2"/*; do
ext=${f##*.}
# Probably more efficient to check in-shell if the directory
# already exists than to start a new process to make the check
# for you.
[[ -d $ext ]] || mkdir "$ext"
mv "$f" "$ext"
done
需要权衡的是,您需要在确定公共(public)扩展之前确定需要做多少工作,以最大程度地减少第二个 for
循环的迭代次数。
关于bash - 基于 bash 中的扩展名有效移动 50 万个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36360574/