【问题标题】:Need a bash scripts to move files to sub folders automatically需要一个 bash 脚本来自动将文件移动到子文件夹
【发布时间】:2012-05-01 19:00:47
【问题描述】:

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

【问题讨论】:

  • 你会想了解像 cp 和 mkdir 这样的命令。互联网上可能有一些关于它们的信息。你也可以谷歌“bash”

标签: bash


【解决方案1】:

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

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

【讨论】:

  • 谢谢,但我得到错误 mv: cannot stat `[A-FA-f]*': No such file or directory
【解决方案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

【讨论】:

  • 这假设您已经创建了文件夹。否则使用 mkdir 创建它们。
【解决方案3】:

这是我的问题:

#!/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)
  • 处理大量文件
  • 如果文件不可移动,则不会发出喙
  • 必要时创建子目录
  • 不会因不寻常的文件名而中断
  • 相对便宜

【讨论】:

  • 对于这个脚本,我得到这个错误:~/root/ok.sh: line 17: syntax error near unexpected token &lt;' /root/ok.sh: line 17: done
  • 你使用的是什么版本的bash
【解决方案4】:

任何脚本语言都可以,所以我在这里用 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)

【讨论】:

  • 是的会很慢,一般移动320G需要很长时间。此外,如果您真的希望它们是随机的,则需要更长的时间。我实际上不建议使用random.choice,而是将子目录分成 5 个偶数部分,然后根据它移动它们。
【解决方案5】:
mv `ls | while read x; do echo "`expr $RANDOM % 1000`:$x"; done \
| sort -n| sed 's/[0-9]*://' | head -1` ./DIRNAME

在你当前的镜像目录中运行它,这个命令将一次选择一个文件并将它移动到./DIRNAME,重复这个命令直到没有更多的文件可以移动。

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

【讨论】:

    猜你喜欢
    • 2012-12-09
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多