将文件夹拆分为子文件夹,子文件夹的名称取决于文件名前缀

将文件夹拆分为子文件夹,子文件夹的名称取决于文件名前缀

我有一个文件夹,里面存储了 8857429 个文件。每个文件都遵循相同的命名结构:“{GROUP}-{UNIX TIMESTAMP}”

我希望每个组都有其子文件夹,其中包含与该组匹配的所有文件。

我如何使用 bash 在 ubuntu 中实现这一点?

我想要的例子:

输入:

DATA/
├── A-1.txt
├── A-2.txt
├── A-3.txt
├── B-1.txt
├── B-2.txt
├── B-3.txt
├── C-1.txt
├── C-2.txt
└── C-3.txt

输出:

DATA/
├── A/
│   ├── 1.txt
│   ├── 2.txt
│   └── 3.txt
├── B/
│   ├── 1.txt
│   ├── 2.txt
│   └── 3.txt
└── C/
    ├── 1.txt
    ├── 2.txt
    └── 3.txt

答案1

  1. 复制下面的脚本并将其保存为./move_files.sh与目录同级命名的文件DATA(即不在DATA目录内)。

  2. 通过执行...使文件可执行

    chmod +x move_files.sh
    
  3. 通过执行...来运行此脚本...

    ./move_files.sh
    

    我建议在你的目录副本上测试此脚本DATA,以确保你获得预期的结果。我只在你问题中分片的确切样本上测试了它。


这是脚本move_files.sh...

#!/bin/bash

# move_files.sh
#
# Creates group folders based on file name prefixes, and then renames
# and moves the files into the corresponding group folders.
#
# All files must be in the "DATA" directory.
# All files must follow the naming structure "{GROUP}-{UNIX TIMESTAMP}".
#
# Remember to make this script executable using `chmod +x move_files.sh`.
# Save this script at the same level as the DATA directory.
# Run this script using `./move_files.sh`

cd "DATA"
count=0
for file_name in *; do
    # Remove the prefix from the file name.
    new_file_name=${file_name#*-}
    # Remove the suffix from the file name.
    group=${file_name%"-$new_file_name"}
    # Print information.
    ((count=count+1))
    echo "${count}. Move file \"${new_file_name}\" into directory \"${group}\"."
    # Create a group directory, if it does not exist.
    mkdir --parents "${group}"
    # Move the file into the group directory, and use the new file name.
    mv "${file_name}" "${group}/${new_file_name}"
done

相关内容