如何将文件放入以其前缀名称命名的文件夹中?

如何将文件放入以其前缀名称命名的文件夹中?

我在一个文件夹中有数千个文件,我想将具有相同前缀的文件放在以前缀相同名称命名的文件夹中。

   -folder
      -a_1.txt
      -a_2.txt
      -a_3.txt
      -b_1.txt
      -b_2.txt
      -b_3.txt

我希望输出是这样的:

   -a
     -1.txt
     -2.txt
     -3.txt
   -b
     -1.txt
     -2.txt
     -3.txt

答案1

使用find -exec

find folder -name "*.txt" \
    -exec sh -c 'f="$(basename "$1")"; mkdir -p "${f%%_*}"; mv "$1" "${f%%_*}"/"${f#*_}"' find-sh {} \;

_如果文件名中有多个。这将在第一个之后剪切_。如果您想在最后一个之后剪切,请将+
替换为+ 。f%%f#f%f##_

答案2

这是一个 Python 脚本,它将 a_1.txt、a_2.txt、a_3.txt 移动到名为 a 的文件夹,并将 b_1.txt、b_3.txt 移动到名为 b 的文件夹,但保留原有名称:

# Import the needed packages
import glob
import shutil
import os
import re
import sys

def copy_(file_path, dest):
    try:
        # get the prfix from the filepath
        pref = re.search(r'(.*)_\d*', file_path).group(1)
        # Check if the folder already exists and create it if not
        if not os.path.exists(dest + '/' + pref.split('/')[-1]):
            os.makedirs(dest + '/' + pref.split('/')[-1])
        # copy the file to the folder
        shutil.move(file_path,
                     dest + '/' + pref.split('/')[-1] + '/' + file_path.split('/')[-1])
    except Exception as e:
        print(e)
        print('there was a problem copying {} to the directory'.format(file_path))
        pass

# Set the directory containing the folders
dirname = sys.argv[1]
# Set the directory that you want to create the folders in
dest = sys.argv[2]
for filepath in glob.glob(dirname + '/**'):
    copy_(filepath, dest)

要运行该脚本,请将其保存到file.py然后使用python file.py dir1 dir2其中 dir1 是文件所在的文件夹,dir2 是要保存新文件夹的文件夹来 运行它

前:

dir1
├── a_1.txt
├── a_2.txt,
├── a_3.txt
├── b_1.txt
├── b_2.txt,
└── b_3.txt

后:

dir2
├── a
│   ├── a_1.txt
│   ├── a_2.txt,
│   └── a_3.txt
└── b
    ├── b_1.txt
    ├── b_2.txt,
    └── b_3.txt

答案3

创建一个 bash shell 脚本,类似:

#!/bin/bash

# Prefix length of the file in chars 1...x 
PREFIXLENGTH=1

for file in *.txt
do  
    # define the folder name
    prefix=${file:0:$PREFIXLENGTH}

    # always mkdir here and fetch the error message
    # can also be made with an if..then     
    mkdir $prefix 2>/dev/null

    # split the rest of the file and move it to folder
    mv "$file" "$prefix/${file:$PREFIXLENGTH}"
done

在文件列表目录中调用它,然后给出:

$ ls a b
a:
    _1.txt  _2.txt  _3.txt

b:
    _1.txt  _2.txt  _3.txt

相关内容