简体   繁体   中英

Extract first (and last) part of file name and copy them to new directory

I am trying to write a Windows batch script to extract the first and last parts of a filename.

I have multiple files named like this:

"John Doe_RandomWalk_4202.m"

"Tim Meyer_plot_3c_4163.pdf"

I would like to make directories like so:

Directory "John Doe" contains "RandomWalk.m"
Directory "Time Meyer" contains "plot_3c.pdf"

They seem to follow this pattern: "FirstName LastName_filename_[number].extension"

I'm not too competed with regex. I'm trying to do this with a windows batch script, however I am open to solutions in another language like Python etc.

Here is what I came up with: Sorry for not including my attempt earlier. Here is what I came up with, its rather messy:

   import os,re

   reg_exp = re.compile('_\d\d')

   filename = "John Doe_RandomWalk_4202.m" ;

   extension = filename.split('.')[-1];

   directory_name = filename.split('_')[0];

   desired_filename = filename.split('_')[1];

   final_filename = desired_filename + '.' + extension

Thanks

If neither firstname nor lastname can contain an underscore, then you don't need regular expressions.

#!/usr/bin/python

import collections, os, shutil

directory_structure = collections.defaultdict(list)

for orig_filename in list_of_your_files:
    name, *filename, extension = orig_filename.split("_")
    extension = "." + extension.split(".")[-1]
    filename = '_'.join(filename) + extension
    directory_structure[name].append((filename,orig_filename))

for directory, filenames in directory_structure.items():
    try:
        os.mkdir(directory)
    except OSError:
        pass # directory already exists
    for filename in filenames:
        newfile, oldfile = filename
        shutil.copyfile(oldfile, os.path.join(directory,newfile))

If you're doing this using absolute paths, this becomes a little more difficult because you'll have to use os.path to strip off the filename from the rest of the path, then join it back together for the shutil.copyfile , but I don't see anything about absolute paths in your question.

Since you were originally hoping for a batch implementation and I'm terrible at Python...

@echo off
setlocal enabledelayedexpansion

set "source_dir=C:\path\to\where\your\files\are"
set "target_dir=C:\path\to\where\your\files\will\be"

:: Get a list of all files in the source directory
for /F "tokens=1,* delims=_" %%A in ('dir /b "%source_dir%"') do (
    set "folder_name=%%A"
    set name_part=%%~nB
    set file_ext=%%~xB

    REM Make a new directory based on the name if it does not exist
    if not exist "!target_dir!\!folder_name!" mkdir "!target_dir!\!folder_name!"

    REM Drop the last token from the name_part and store the new value in the new_filename variable
    call :dropLastToken !name_part! new_filename

    REM If you want to move instead of copy, change "copy" to "move"
    copy "!source_dir!\!folder_name!_!name_part!!file_ext!" "!target_dir!\!folder_name!\!new_filename!!file_ext!"
)

:: End the script so that the function doesn't get called at the very end with no parameters
exit /b

:dropLastToken
setlocal enabledelayedexpansion
set f_name=%1

:: Replace underscores with spaces for later splitting
set f_name=!f_name:_= !

:: Get the last token
for %%D in (!f_name!) do set last_token=%%D

:: Remove the last_token substring from new_filename
set f_name=!f_name: %last_token%=!

:: Put the underscores back
set f_name=!f_name: =_!

endlocal&set %2=%f_name%

Since we don't know the structure of the filenames beforehand, a regex might suit you better. Here's an implementation in Python:

import os
import re

# Grab everything in this directory that is a file

files = [x for x in os.listdir(".") if os.path.isfile(x)]

# A dictionary of name: filename pairs.
output = {}

for f in files:

    """
    Match against the parts we need:

    ^ --> starts with
    ([a-zA-Z]+) --> one or more alphanumeric characters 
                        or underscores (group 1)
    \s+ --> followed by one or more spaces
    ([a-zA-Z]+)_ --> Another alphanumeric block, followed
                                by an underscore (group 2)
    (\w+) --> A block of alphanumeric characters or underscores (group 3)
    _\d+\. --> Underscore, one or more digits, and a period
    (.+) --> One or more characters (not EOL) (group 4)
    $ --> End of string

    """
    m = re.match("^([a-zA-Z]+)\s+([a-zA-Z]+)_(\w+)_\d+\.(.+)$", f)
    if m:
        # If we match, grab the parts we need and stuff it in our dict
        name = m.group(1) + " " + m.group(2)
        filename = m.group(3) + "." + m.group(4)

        output[name] = filename

for name in output:
    print 'Directory "{}" contains "{}"'.format(name, output[name])

Note that this isn't optimally compact, but is relatively easy to read. You should also be able to do:

import os
import re

output = {name: filename for (name, filename) in [
    (m.group(1) + " " + m.group(2), m.group(3) + "." + m.group(4))
        for m in [
            re.match("^(\w+)\s+([a-zA-Z]+)_(\w+)_\d+\.(.+)$", f)
                for f in os.listdir(".") if os.path.isfile(f)
                ]
        if m
    ]
}

With my limited python experience I came up with this. It works, though probably not the best way:

import collections, os, shutil

list_of_your_files = [f for f in os.listdir('.') if os.path.isfile(f)];

for filename in list_of_your_files:

    extension = filename.split('.')[-1];

    directory = filename.split('_')[0];

    desired_filename = filename.split('_')[1];

    final_filename = desired_filename + '.' + extension

    try:
        os.mkdir(directory)
    except OSError:
        pass # directory already exists

    ##newfile, oldfile = final_filename
    shutil.copyfile(filename, os.path.join(directory,final_filename))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM