Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

windows - How do I create folder from file name and move files into folder?

I need a windows batch file to create a folder based on part of a file name (the part before an underscore) and move any files that start with the folder name into the folder.

I'm not familiar with windows batch files. I've googled and tinkered a solution which works except that I cannot substring the file name at the underscore.

(Yes there are a few similar threads but nothing I could use to exactly answer my question)

FWIW my unsuccessful solution:

@ECHO OFF
setlocal enabledelayedexpansion
SETLOCAL

SET "sourcedir=C:Development	est"
PUSHD %sourcedir%
FOR /f "tokens=1*" %%a IN (
 'dir /b /a-d "TTT*_*.*"'
 ) DO (  

 ECHO MD NEED FILE NAME BEFORE UNDERSCORE HERE
 ECHO MOVE "%%a" .NEED FILE NAME BEFORE UNDERSCORE HERE
)

(Ideally I'd remove the leading 'TTT' from files too but if necessary can create the files without this.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this batch file code:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceDir=C:Development	est"
set "DestDir=C:Development	est"

for /F "eol=| delims=" %%A in ('dir /B /A-D-H "%SourceDir%TTT*_*" 2^>nul') do (
    for /F "eol=| tokens=1 delims=_" %%B in ("%%~nA") do (
        md "%DestDir%\%%B" 2>nul
        move /Y "%SourceDir%\%%A" "%DestDir%\%%B"
    )
)

endlocal

The first FOR executes in a separate command process started with cmd.exe /C in background the command line:

dir /B /A-D-H "C:Development	estTTT*_*" 2>nul

DIR searches in specified directory for

  • just non-hidden files because of /A-D-H (attribute not directory and not hidden)
  • matching the wildcard pattern TTT*_* which could be also just *_*
  • and outputs to handle STDOUT in bare format because of /B just the file names with file extension, but without file path.

The error message output by DIR to handle STDERR if the specified directory does not exist at all or there is no file matching the pattern is suppressed by redirecting it with 2>nul to device NUL.

Read also the Microsoft documentation about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line in a separate command process started in background.

FOR captures everything written to STDOUT of started command process and processes the captured output line by line.

FOR ignores by default all empty lines (do not occur here) and all lines starting with a semicolon. A file name could begin with a semicolon. For that reason option eol=| is used to redefine end of line character to vertical bar which a file name can't contain, see Microsoft documentation Naming Files, Paths, and Namespaces. In this case on using TTT*_* as wildcard pattern it is not possible that a file name starts with a semicolon, but it would be possible on usage of *_* as wildcard pattern.

FOR would split up also each line into substrings (tokens) using space/tab as delimiters and would assign just the first space/tab separated string to specified loop variable A. This splitting behavior is not wanted here as file names can contain one or more space characters. Therefore the option delims= is used to define an empty list of delimiters which disables line splitting completely and results in assigning entire file name with extension to loop variable A.

The inner FOR processes just the file name (without extension) as string. This time the file name is split up using the underscore as delimiter because of delims=_ with assigning just first underscore delimited string to loop variable B because of tokens=1. Well, tokens=1 is the default on using for /F and so this option string could be removed from code.

So the outer FOR assigns to A for example TTTxy_test & example!.txt and the inner FOR processes TTTxy_test & example! and assigns to B the string TTTxy.

The command MD creates in set destination directory a subdirectory for example with name TTTxy. An error message is output also on directory already existing. This error message is suppressed by redirecting it to device NUL.

Then the file is moved from source to perhaps just created subdirectory in destination directory with overwriting an existing file with same name in target directory of the file.

The inner FOR loop could be optimized away when there are never files starting with an underscore or which have more than one underscore after first part of file name up to first underscore.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceDir=C:Development	est"
set "DestDir=C:Development	est"

for /F "eol=| tokens=1* delims=_" %%A in ('dir /B /A-D-H "%SourceDir%TTT*_*" 2^>nul') do (
    md "%DestDir%\%%A" 2>nul
    move /Y "%SourceDir%\%%A_%%B" "%DestDir%\%%A"
)

endlocal

Option tokens=1* results in assigning first underscore delimited part of file name to loop variable A and rest of file name to next loop variable B according to ASCII table without further splitting up on underscores.

But please take into account that the optimized version does not work for file names like

  • _TTTxy_test & example!.txt ... underscore at beginning (ignored by pattern), or
  • TTTxy__test & example!.txt ... more than one underscore after first part.

The optimized version can be further optimized to a single command line:

@for /F "eol=| tokens=1* delims=_" %%A in ('dir /B /A-D-H "C:Development	estTTT*_*" 2^>nul') do @md "C:Development	est\%%A" 2>nul & move /Y "C:Development	est\%%A_%%B" "C:Development	est\%%A"

Well, the not optimized version could be also written as even longer single command line:

@for /F "eol=| delims=" %%A in ('dir /B /A-D-H "C:Development	estTTT*_*" 2^>nul') do @for /F "eol=| tokens=1 delims=_" %%B in ("%%~nA") do @md "C:Development	est\%%B" 2>nul & move /Y "C:Development	est\%%A" "C:Development	est\%%B"

See also Single line with multiple commands using Windows batch file for an explanation of operator &.

For additionally removing TTT from file name on moving the file the first batch code is modified with using two additional commands SET and CALL:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceDir=C:Development	est"
set "DestDir=C:Development	est"

for /F "eol=| delims=" %%A in ('dir /B /A-D-H "%SourceDir%TTT*_*" 2^>nul') do (
    for /F "eol=| tokens=1 delims=_" %%B in ("%%~nA") do (
        md "%DestDir%\%%B" 2>nul
        set "FileName=%%A"
        call move /Y "%SourceDir%\%%A" "%DestDir%\%%B\%%FileName:~3%%"
    )
)

endlocal

The file name is assigned to an environment variable FileName. The value of this environment variable cannot be referenced with just using %FileName% because of all references of environment variable values using percent signs are substituted by Windows command processor in entire command block starting with first ( and ending with matching ) before FOR is executed at all. Delayed expansion is usually used in such cases, but that would result here in file names containing one or more exclamation marks would not be corrected processed by the batch file.

The solution is using %% on both sides of FileName environment variable reference instead of % and force a double parsing of the command line by using command CALL.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • call /?
  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • md /?
  • move /?
  • set /?
  • setlocal /?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...