2

我有一个包含 320G 图像的文件夹,我想将图像随机移动到 5 个子文件夹(只需移动到 5 个子文件夹)。但我对 bash 脚本一无所知。请有人帮忙吗?谢谢!

4

5 回答 5

3

您可以根据文件的第一个字母将文件移动到不同的目录:

mv [A-Fa-f]* dir1
mv [F-Kf-k]* dir2
mv [^A-Ka-k]* dir3
于 2012-05-01T07:00:59.447 回答
2

这是我对此的看法。为了使用它,将脚本放在其他地方(不在您的文件夹中),但从您的文件夹中运行它。如果你调用你的脚本文件 rmove.sh,你可以把它放在,比如说 ~/scripts/,然后 cd 到你的文件夹并运行:

源 ~/scripts/rmove.sh

#/bin/bash

ndirs=$((`find -type d | wc -l` - 1))

for file in *; do
        if [ -f "${file}" ]; then
                rand=`dd if=/dev/random bs=1 count=1 2>/dev/null | hexdump -b | head -n1 | cut -d" " -f2`
                rand=$((rand % ndirs))

                i=0
                for directory in `find -type d`; do
                        if [ "${directory}" = . ]; then
                                continue
                        fi
                        if [ $i -eq $rand ]; then
                                mv "${file}" "${directory}"
                        fi
                        i=$((i + 1))
                done
        fi
done
于 2012-05-01T07:24:20.703 回答
2

Here's my stab at the problem:

#!/usr/bin/env bash

sdprefix=subdir
dirs=5

# pre-create all possible sub dirs
for n in {1..5} ; do
    mkdir -p "${sdprefix}$n"
done

fcount=$(find . -maxdepth 1 -type f | wc -l)

while IFS= read -r -d $'\0' file ; do
    subdir="${sdprefix}"$(expr \( $RANDOM % $dirs \) + 1)

    mv -f "$file" "$subdir"
done < <(find . -maxdepth 1 -type f -print0)
  • Works with huge numbers of files
  • Does not beak if a file is not moveable
  • Creates subdirectories if necessary
  • Does not break on unusual file names
  • Relatively cheap
于 2012-05-01T11:00:47.887 回答
1

任何脚本语言都可以,所以我将在这里用 Python 编写:

#!/usr/bin/python

import os
import random

new_paths = ['/path1', '/path2', '/path3', '/path4', '/path5']
image_directory = '/path/to/images'
for file_path in os.listdir(image_directory):
    full_path = os.path.abspath(os.path.join(image_directory, file_path))

    random_subdir = random.choice(new_paths)
    new_path = os.path.abspath(os.path.join(random_subdir, file_path))

    os.rename(full_path, new_path)
于 2012-05-01T07:01:06.230 回答
-1
mv `ls | while read x; do echo "`expr $RANDOM % 1000`:$x"; done \
| sort -n| sed 's/[0-9]*://' | head -1` ./DIRNAME

在您当前的图像目录中运行它,此命令将一次选择一个文件并将其移动到./DIRNAME,迭代此命令直到没有更多文件可移动。

请注意 ` 是反引号,而不仅仅是引号字符。

于 2012-05-01T07:10:41.177 回答