Nested FOR with variables - windows

I'm attempting to write a batch script that will go through a list of computers, read a file from the computer, delim the file name, then echo the computer name and the file name result. The issue I'm having is getting the computer name variable to populate in the nested FOR /R command. Here is my script:
#ECHO OFF
SetLocal EnableDelayedExpansion
SET LIST=Computers.txt
FOR /F %%A IN (%LIST%) DO (
FOR /R \\%%A\c$\folder1\folder2 %%B IN (*.txt) DO (
FOR /F "tokens=2 delims=." %%C IN ("%%B") DO (ECHO %%A %%C
)
)
)
EndLocal
The filename is something like RB-C1SRC20160716CL.P17.txt. So the result I am looking for is
MyPCName P17
But I get a blank result. What I have found is that %%A var is being populated from the text file but the %%A var in the FOR /R is not populating. If I ECHO ON the FOR commands I'm seeing FOR /R \%a\folder1\folder2 instead of FOR /R \MyPCName\folder1\folder2. This breakdown is keeping the rest of the script from working properly.

The root directory of a for /R command cannot be given by another for variable (like %%I) nor a variable using delayed expansion (!VAR!), unfortunately. You need to specify it either iterally, by a normally expanded variable (%VAR%) or by an argument reference (%1, %2,...).
A good work-around is to place the for /R loop in a sub-routine and use call to call it from your main routine. The (variable holding the) root path needs to be passed as an argument to call. In the sub-routine it is referred to by an argument reference (like %1).
Take a look at this answer of the post "Get size of the sub folders only using batch command" to see how this can be accomplished.
Another option is to temporarily change into the root directory before the for /R loop, which then defaults to the current working directory. Use pushd"\\%%A\c$\folder1\folder2" to change to the target directory, then put popd behind the for /R loop to return to the former directory.

Related

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\test"
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.)
Try this batch file code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceDir=C:\Development\test"
set "DestDir=C:\Development\test"
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\test\TTT*_*" 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 with using 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\test"
set "DestDir=C:\Development\test"
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\test\TTT*_*" 2^>nul') do #md "C:\Development\test\%%A" 2>nul & move /Y "C:\Development\test\%%A_%%B" "C:\Development\test\%%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\test\TTT*_*" 2^>nul') do #for /F "eol=| tokens=1 delims=_" %%B in ("%%~nA") do #md "C:\Development\test\%%B" 2>nul & move /Y "C:\Development\test\%%A" "C:\Development\test\%%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\test"
set "DestDir=C:\Development\test"
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 /?
It is really very simple:
#echo off
for /f "tokens=1-2 delims=_" %%i in ('dir /b /a-d "TTT*_*"') do (
if not exist "%%i" mkdir "%%i"
move "%%i_%%j" "%%i\%%j"
)
We split by _ into 2 tokens, %%i everything before _ and %%j everything after.
We simply create folder (if it does not exist) then move the file with only the name after the _ into the new folder.
So as an example file TTT123_File1.txt will create a folder called TTT123 and place the file into it but rename it as File1.txt
You might consider using Tcl/Tk. Tcl/Tk is an open source script language. You can call it as a stand-alone or execute it from a windows batch file. You will need to install it first if you don't have it yet.
The following Tcl script does what you want:
cd "C:/Development/test"
# glob is a tcl command to list all functions that match the requirements
set files [glob TTT*_*]
foreach f $files {
# use the underscore as a separator to split f and store the parts in dir and fnew
lassign [split $f "_"] dir fnew
if {![file exist $dir]} {
file mkdir $dir
}
file rename $f [file join $dir $fnew]
}
In my opinion, this is a very readable script, even if you don't know tcl.
You can call this script from a batch file as:
tclsh script.tcl
if you have saved the script as script.tcl

.bat renaming the file with the content inside the parentheses

So, previously I was here because I wanted to rename my file based on something that I created, I ended up doing it and it was a simple thing, but now, I am with another thing that I think it's better, so I have this code:
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
chcp 65001
SET "sourcedir=C:\Users\leandro.batista\Desktop\SAMPLES RENAMER"
SET "destdir=C:\Users\leandro.batista\Desktop\SAMPLES RENAMER\BACKUP"
FOR /f "delims=()" %%a IN ('dir /b /a-d "%sourcedir%\*.pdf" ') DO (
REN "%%a" "%sourcedir%\*.pdf"
PAUSE
)
I tried to rename the file with what was inside the parentheses of the file name, for exemple :
Input:
File Name: blablabla(exampleIwantToExtract)
OutPut:
File Name: (exampleIwantToExtract)
When I run the bat it says that has a syntax error and I am not pretty sure why, I have an ideia tho, it might be the REN code, or better, it must be the REN code.
if you use delims, you should also use the right token (2 for your example filename(s). If you don't define it, it defaults to 1, which would give you blablabla)
But for renaming a file, you need also the full name. Best method is to use two nested forloops. The outer loop a plain for to get the (old) filename and an inner for /f loop to tokenize the filename to get the new name:
for %%a in ("%sourcedir%\*.pdf") do (
for /f "tokens=2 delims=()" %%b in ("%%~na") do (
ECHO move "%%~fa" "%destdir%\(%%b)%%~xa"
)
)
%%~fa gives you the full qualified file name (including drive and path)
%%~na gives you the name of the file only
%%~xa gives you the extension of the file (of course you could simply type .pdf instead,
but %%~xa gives you additional flexibility)
Note: ren doesn't support destination path. Therefore I used move instead.

Trim Date from file name windows script

How do you trim the date from a text file. For example, I have multiple files like:
test_MX_abc_20091011.txt
test_MX_pqrdhdsu_20091011.txt
test_MX_xyieuz_20091011.txt
All files will have test_MX in common but the 3rd part will of different size.
I would like to change into:
test_MX_abc.txt
test_MX_pqrdhdsu.txt
test_MX_xyieuz.txt
I know how to change the file if name is like test_20091011.txt with the below code, But if name has more string along with date, how to do that?
for /F "tokens=1 delims=_" %%i in ("%%~na") do (
move /Y %%~fa %data_in%\%%i%%~xa >nul
)
Thanks in advance.
This rename operation can be done for example with:
#echo off
for /F "tokens=1-3* delims=_" %%A in ('dir /A-D /B test_MX_*.txt') do (
ren "%%A_%%B_%%C_%%D" "%%A_%%B_%%C.txt"
)
Each file name is separated into 4 strings assigned to loop variables A to D with using underscore as separator. The loop variable D takes everything of file name after third underscore.
Or also working for the 3 files:
#echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%F in ('dir /A-D /B test_MX_*.txt') do (
set "ActFileName=%%~nF"
set "NewFileName=!ActFileName:~0,-9!"
ren "%%~F" "!NewFileName!.txt"
)
endlocal
This solution assigns the name of a file without file extension and path to environment variable ActFileName. Next a new environment variable with name NewFileName is defined with name of active file without the last 9 characters (underscore and date string). This modified file name is used next in the rename operation.
Other solutions using commands for, set and ren can be found on Stack Overflow.
Search with the string
[batch-file] for set rename files
and more than 600 results are presented all using more or less something like above.
For details on the used commands, open a command prompt window, execute one after the other following commands and read output help.
dir /?
for /?
ren /?
set /?

For loop copying files in command prompt using a substring to name the destination for each file (with delayed expansion)

I have a directory of files and a seperate directory filled with folders with names that correspond to a substring of the file name. I'm trying to cycle through a list of files and for each one, where there is a folder with the corresponding substring name, deposit a copy of the file into it. Where there is no corresponding folder, I need the file to be ignored. This can't be done in a batch file, it needs to be done in command prompt.
I'm having the problem that the initial response to my command
for /f %I in ('dir /b J:\test\test_audio\en * ^| find ".wav"') do (
set var=I
copy J:\test\test_audio\en\%~I J:\test\test_designed_locations\%var:~0,5%\
)
is The syntax of the command is incorrect, due I think to the order of expansion of the command.
....
C:\Windows\System32>(
set var=Ev164_en.wav
copy J:\test\test_audio\en\Ev164_en.wav J:\test\test_designed_locations\%var:~0,5%\
)
The syntax of the command is incorrect
C:\Windows\System32>(
set var=Ev178_en.wav
copy J:\test\test_audio\en\Ev178_en.wav J:\test\test_designed_locations\%var:~0,5%\
)
The syntax of the command is incorrect
...
This would also explain why running the command a second time creates a situation where the substring from the last file is used in all commands, causing every file to be deposited in the last folder and none in the others.
....
for /f %I in ('dir /b J:\test\test_audio\en * ^| find ".wav"') do (
set var=I
copy J:\test\test_audio\en\157_en.wav J:\test\test_designed_locations\Ev225\
)
1 file(s) copied.
for /f %I in ('dir /b J:\test\test_audio\en * ^| find ".wav"') do (
set var=I
copy J:\test\test_audio\en\158_en.wav J:\test\test_designed_locations\Ev225\
)
1 file(s) copied.
....
I suspect that I need to use delayed expansion to stop environment variables being processed and overwriting each other before use. I've tried adding setLocal enableDelayedExpansion at the start of the command and wrapping the reference to the variable in bangs
setLocal enableDelayedExpansion
for /f %I in ('dir /b J:\test\test_audio\en * ^| find ".wav"') do (
set var=%I
copy J:\test\test_audio\en\%~I J:\test\test_designed_locations\!var:~0,5!\
)
With or without the an escape before the comma, I get
....
C:\Windows\System32>(
set var=Ev164_en.wav
copy J:\test\test_audio\en\Ev164_en.wav J:\test\test_designed_locations\!var:~0,5!\
)
The syntax of the command is incorrect.
....
The variable isn't being processed for its value. I'm starting to wonder if it's actually possible to for-loop through all the files and use a substring from each file name to identify where to put that file, all in one command. Any help much appreciated.
cmd /v /q /c "pushd "j:\test\test_audio\en" && ( for %a in (*.wav) do ( set "I=%~nxa" & if exist "!I:~0,5!\" copy "%a" "!I:~0,5!" ) & popd )"
You can use delayed expansion from command line only if the cmd instance is started with it enabled.
edited to adapt to comments
pushd "j:\test\test_audio\en" && (for %a in (*.wav) do (set "I=%~nxa" & call pushd ^"%I:~0,5^%^" 2>nul &&(copy "%~fa" & popd)) & popd)
Well, it can be done without starting a separate cmd instance to enable delayed expansion, but the needed escaping to use a call to force a second parser evaluation of the line is not very obvious.

how to replace names recursively via windows batch operation

I want to process a batch operation in a big directory. Actually I have the batch script for that process. But here , I have a problem. Some of the directory names, files names contain " " (space character). So in the batch operation this names passed as 2 arguments . and those lines will not work. So Iwant to rename " " with "_" to overcome this problem .
Example:
process /MyDirectory/Ola and Me/Private/TopSecretPictures/
this gives error. the below one works fine
process /MyDirectory/Ola and Me/Private/TopSecretPictures
My aim is: convert | Ola and Me |>> |Ola_And_Me recursively
:)
thanks in advance ..
The following script renames all files and directories recursively, starting at a given directory, converting spaces to underscores.
spaces_to_underscores.bat source:
#echo off
setlocal
for /r "%~1" %%t in (.) do (
for /f "usebackq tokens=*" %%f in (`dir /b/a-d "%%~t" 2^>nul:`) do (
call :proc "%%~f" "%%~t"
)
for /f "usebackq tokens=*" %%d in (`dir /b/ad "%%~t" 2^>nul:`) do (
call :proc "%%~d" "%%~t"
)
)
exit /b 0
:proc
set fn=%~1
if "%fn: =_%"=="%fn%" exit /b 0
set fn=%~2\%fn: =_%
move "%~2\%~1" "%fn%" >nul:
exit /b 0
Usage:
spaces_to_underscores "My Directory"
Given this directory structure
My Directory
Ola and Me
Private
TopSecretPictures
it will rename the folder "Ola and Me" to "Ola_and_Me", and also rename any files such as "Photo 001.jpg" to "Photo_001.jpg". The starting directory "My Directory" will not be renamed.
WARNING: Do not run this script on standard windows directories, such as "C:\Documents and Settings" or "C:\Program Files" or "My Documents" or "Application Data". There is no "undo" functionality here. Make sure you have a backup.
You can do this in a batch file if you use a feature called "delayed exapansion" that isn't on by default. To switch it on, you need to start cmd.exe with the /v switch:
cmd.exe /v
Once this is on, the following batch script will replace all spaces in %%i with underscores, and spit the result out:
for /f "usebackq tokens=*" %%i in (`dir /b`) do (
set S=%%i
set T=!S: =_!
echo !T!
)
***Vauge description...***Excluding the for loop itself, the interesting parts of this are:
String substitution using the %var:str1=str2% syntax
Delayed expansion using !var! instead of %var%
First: delayed expansion... without this, the command interpreter (for whatever reason Microsoft decided to code it as) will evaluate all the parameters first, and then run the script: so this version of the script does NOT work:
for /f "usebackq tokens=*" %%i in (`dir /b`) do (
set S=%%i
set T=%S: =_%
echo %T%
)
With this version the variable 'T' is set to the last value of the for loop before the contents of the (...) block actually execute. Which makes no sense to me. So with delayed execution enabled, we can use the delayed execution variable marks, i.e., !var! rather than %var%. Which gives us the right result.
The other clever bit then is the set T=!S: =_! (which basically says set T to S, replacing every '' ' in S with '_'). Without delayed expansion, this would be written set T=%S: =_%.

Resources