需要bash脚本自动将文件移动到子文件夹

时间:2012-05-01 06:54:36

标签: bash

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

5 个答案:

答案 0 :(得分:3)

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

mv [A-Fa-f]* dir1
mv [F-Kf-k]* dir2
mv [^A-Ka-k]* dir3

答案 1 :(得分:2)

这是我对此的看法。为了使用它,将脚本放在其他位置(不在您的文件夹中),而是从您的文件夹中运行它。如果您调用脚本文件rmove.sh,可以将其放入,例如〜/ scripts /,然后cd到您的文件夹并运行:

  

source~ / 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

答案 2 :(得分:2)

这是我对这个问题的准备:

#!/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)
  • 使用大量文件
  • 如果文件不可移动,则不会发出喙
  • 根据需要创建子目录
  • 不会破坏不寻常的文件名
  • 相对便宜

答案 3 :(得分: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)

答案 4 :(得分:-1)

mv `ls | while read x; do echo "`expr $RANDOM % 1000`:$x"; done \
| sort -n| sed 's/[0-9]*://' | head -1` ./DIRNAME

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

注意`是反引号而不只是引用字符。

相关问题