【问题标题】:How to randomly distribute the files across 3 folders using Bash script?如何使用 Bash 脚本将文件随机分布在 3 个文件夹中?
【发布时间】:2021-04-06 05:30:36
【问题描述】:

mydata/files 文件夹中有很多子目录和文件。我想把文件随机复制到3个文件夹中:

train
test
dev

例如,mydata/files/ss/file1.wav 可以复制到 train 文件夹中:

train
  file1.wav

以此类推,直到所有来自mydata/files 的文件都被复制。

我如何使用 Bash 脚本来做到这一点?

【问题讨论】:

  • 你尝试了什么?
  • @0stone0 我在 Python 中实现了它,但在 Bash 中无法实现,因为我对 Bash 的了解非常有限。
  • 不要重新发明sklearn轮子。

标签: linux bash


【解决方案1】:

您可以创建一个临时文件,将您的目标文件夹回显到其中,然后使用shuf 命令。

dest=$(mktemp)
echo -e "test\ndev\ntrain" >> $dest
while IFS= read -r file; do
  mv "$file" "$(shuf -n1 < $dest)/."
done < <(find mydata/files -type f 2>/dev/null)
rm -f "$dest"

【讨论】:

    【解决方案2】:

    解决这个问题的步骤:

    1. 需要收集目录下的所有文件
    2. 将目录分配给地图
    3. 为每个文件生成随机数
    4. 将文件移动到对应目录

    脚本:

    #!/bin/bash
    
    original_dir=test/
    
    ## define 3 directories to copy into
    # define an associative array (like a map)
    declare -A target_dirs
    
    target_dirs[0]="/path/to/train/"
    target_dirs[1]="/path/to/test/"
    target_dirs[2]="/path/to/dev/"
    
    # recursively find all the files, and loop through them
    find $original_dir -type f | while read -r file ; do
            # find a random number 0 - (size of target_dirs - 1)
            num=$(($RANDOM % ${#target_dirs[@]}))
            # get that index in the associative array
            target_dir=${target_dirs[$num]}
            # copy the file to that directory
            echo "Copying $file to $target_dir"
            cp $file $target_dir
    done
    

    你需要改变的地方:

    1. 更改目录的目标以匹配系统中的路径
    2. 为文件添加可执行权限,以便您可以运行它。
    chmod 744 copy_script_name
    ./copy_script_name
    

    注意事项:

    如果需要,这个脚本应该很容易扩展到任意数量的目录(只需添加新目录,脚本就会调整随机数。

    如果只需要获取当前目录下的文件(不递归),可以添加 -maxdepth 1(见How to list only files and not directories of a directory Bash?)。

    能够利用以前的 bash 经验以及查看 bash 文档(通常非常好)。如果您最终编写了任何脚本,请非常注意空格

    【讨论】:

      猜你喜欢
      • 2017-08-03
      • 2015-05-20
      • 2023-01-27
      • 2019-08-05
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      相关资源
      最近更新 更多