Nested for loop - batch Script - batch-file

Hello Batch File experts,
I wrote this piece of code which will print the Latest file version present in the folder in comparison to file name sent as argument, however these line seems to work accordingly when I remove the outer for loop, which I designed to loop as many time as CLI arguments.
FOR /f %%f IN ('DIR /b %%a.*.zip') DO #SET last=%%f
ECHO %last%
Full code :
cd C:\Users\batch\Desktop\test
chdir
set arg1=%1
set arg2=%2
set list=%arg1% %arg2%
(for %%a in (%list%) do (
FOR /f %%f IN ('DIR /b %%a.*.zip') DO #SET last=%%f
ECHO %last%
))
pause
what am I missing here because of which variable last is not set with value when outer loop is present which works perfectly without it.
Thanks,

Might I suggest you use SHIFT instead:
#Echo Off
SetLocal
If %1'==' Exit/B
If /I Not "%CD%"=="%USERPROFILE%\Desktop\test" (
PushD "%USERPROFILE%\Desktop\test" 2>Nul&&(Set _=PopD)||Exit/B)
:Loop
For %%A In ("%~1*.zip") Do Set "last=%%A"
Echo=%last%
Shift
If Not %1'==' GoTo Loop
%_%
EndLocal
Timeout -1
This of course means that you are free to use it with more than two arguments!

You need to use delayed expansion (about ten thousand SO items on this) or use a subroutine or
call echo %%last%%

Related

Command works on command line, but operates unexpectedly in batch file

I have this simple batch code to check the Date Modified on a sub-folder (specifically the Recycle Bin.)
This search works flawlessly when manually input in Command Prompt, but not batch.
And using the same exact code to check other folders it works just fine. Help?
Code:
if exist C:\$Recycle.Bin (
pushd "C:\$Recycle.Bin"
for /F "delims=" %%a in ('dir /S /b S-1-*-1001 /AD') do set {file}=%%a
for %%a in ("%{file}%") do echo Recycle Bin: %%~ta
popd
)
The reason this is not working in batch is for one annoying feature of IF statements with the SET command. As stated by This Post - "cmd expands variables when commands are parsed, not when they are run. It so happens that an if or for statement with a block ( ... ) (or actually any block) counds as a single command in that case. So when you set variables inside a block and try using them in the same block there are no variables anymore – they were replaced by the values the variables had before the block even executed." - Joey
To fix this you can simply not put your code block inside the IF statement but rather use an ELSE and have it goto an :EOF
Option 1: - Avoid IF Statement W/H Code Block
#ECHO OFF
Rem | Check If Directory Exists & pushd It.
if exist "C:\$Recycle.Bin" (pushd "C:\$Recycle.Bin") ELSE (goto :EOF)
Rem | Grab data on folders
for /F "delims=" %%a in ('dir /S /b S-1-*-1001 /AD') do (set "{File}=%%a")
Rem | Display data on folders
for %%a in ("%{file}%") do (echo Recycle Bin: %%~ta)
Rem | Un-pushd
popd
pause
goto :EOF
If you do however wish to use a block inside the IF statment you will need to use setlocal enabledelayedexpansion at the top of your script. Furthermore, to echo or read brackets you will have to use !{File}! over %{File}%.
Option 2: - Properly expand IF Statement W/H Code Block
#ECHO OFF
#setlocal enabledelayedexpansion
if exist "C:\$Recycle.Bin" (
pushd "C:\$Recycle.Bin"
for /F "delims=" %%a in ('dir /S /b S-1-*-1001 /AD') do (set "{File}=%%a")
for %%a in ("!{file}!") do (
Set "data=%%~ta"
echo Recycle Bin: !data!
)
popd
) Else (Goto :EOF)
pause
goto :EOF

Batchfile to rename files

Sadly I couldn't yet manage find a working solution but hopefully this time.
Long story short, we got a printer and we are currently unable to configure the scanfolder to our network drives. So I need a script to rename and move the files but keep them all.
As far as I managed to come I got a smart idea to move the files into a firstfolder to avoid that the files are overwritten. Next I need to either rename the files with a counter or move them and keep them all.
I choose the rename option since this seems more simple but I ran into one big issue.
I have no idea how I make it work. So what I'm trying is to first set the variable and do a first test calculation. Just for a first quick test. Now it already works for the first count but sadly it doesn't count up as hoped since he does the rename for all the files before increasing the value of the variable so only one file is renamed.
#ECHO off
::Defining Variables
setlocal EnableDelayedExpansion
SET N=0
ECHO %N% Hi Not rename
SET /a N=%N%+1
FOR /L %%A in (1,1,10) DO (
Echo !N! hi
RENAME "C:\Users\smorheng\Desktop\1\*.pdf" "Test.?????.!N!.*" | SET /a N=!N!+1
ECHO !N! Hi Not rename
timeout 3 /nobreak > nul
)
ECHO RENAME DONE
timeout 50 /nobreak > nul
About 20 Files are renamed to something like Test.1.pdf, Test.2.pdf .... Test.20.pdf and then moved to their destination.
The moving is not an issue but if I could manage to get this feature working I can adapt it to whatever I need.
You can simply move the files, but first check if the file exists in destination, if it does, rename it using a numeric value after the name. Here is something that might work. You just need to change source and destination folder below. The actual move will not occur as I added echo to the second last and last line to demonstrate what it will do, if it works, simply remove echo from both lines.
#echo off
setlocal enabledelayedexpansion
set "source=C:\Users\smorheng\Desktop\1\"
set "dest=D:\destination\folder"
set /a cnt=0
for /f "tokens=*" %%a in ('dir /S /B /A-D "%source%*.pdf"') do for /f "tokens=*" %%b in ('dir /B "%%a"') do if exist "%dest%\%%b" (
set "ext=%%~xa"
set "fname=%%~na"
if exist "%dest%\!fname!(!cnt!)!ext!" (set /a cnt=!cnt!+1)
set /a cnt=!cnt!+1
echo move "%%a" "%dest%\!fname!(!cnt!)!ext!"
) else echo move "%%a" "%dest%\%%b"
Also note, this will recursively move all files from within the directory tree, if you only want to go into the first directory, simply remove /S from the for loop which will then simply become dir /B /A-D "%source%*.pdf"
Edit
As for your for /L loop (mentioned in comment)
Rather have a label and permanently goto it after completed. Here is a simple example of something like that, copy it to a script and run it, see the result:
#echo off
:label
echo Hi, this will run every 6 seconds and print this line. (infinitely).
timeout 6>nul
goto :label
So technically you can do the exact same for your loop, for instance:
#echo off
:label
setlocal enabledelayedexpansion
set "source=C:\Users\smorheng\Desktop\1\"
set "dest=D:\destination\folder"
set /a cnt=0
for /f "tokens=*" %%a in ('dir /S /B /A-D "%source%*.pdf"') do for /f "tokens=*" %%b in ('dir /B "%%a"') do if exist "%dest%\%%b" (
set "ext=%%~xa"
set "fname=%%~na"
if exist "%dest%\!fname!(!cnt!)!ext!" (set /a cnt=!cnt!+1)
set /a cnt=!cnt!+1
echo move "%%a" "%dest%\!fname!(!cnt!)!ext!"
) else echo move "%%a" "%dest%\%%b"
endlocal
timeout 6>nul
goto :label
Try replacing "RENAME" to SET newname see if that helps?
EDIT or try a vbs script instead of a batch?
`Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder="c:\test"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
If objFS.GetExtensionName(strFile) = "jpg" Then
strFileName = strFile.Name
If InStr(strFileName,"XXXXXXX") > 0 Then
strNewFileName = Replace(strFileName,"XXXXX","YYYYY")
strFile.Name = strNewFileName
End If
End If
Next `

how to get the list of files from the directory one by one into a variable

I am new to Batch script,
by using the following code
setlocal enabledelayedexpansion enableextensions
set LIST=
for %%x in (D:\all_files\*.csv) do set LIST=!LIST! %%x
set LIST=%LIST:~1%
echo %LIST%
i am getting the filenames with directory and also with a Paragraph
but i need file names alone one by one like below into a Variable of %LIST%
file1.csv
file2.csv
file3.csv
can any one please help us
I hope, I got your intentions right.
Instead of a variable, just loop over output of dir /b
:loop
echo still waiting...
timeout /t 10
set "ok=yes"
for /f "delims=" %%a in ('dir /b "D:\all_files\*.csv"') do (
if not exist "C:\%%a" set "ok=no"
)
if "%ok%" == "no" goto :loop
echo all there...
call process1.bat

Batch output one occurrence instead of several [duplicate]

Is it possible to remove duplicate rows from a text file? If yes, how?
Sure can, but like most text file processing with batch, it is not pretty, and it is not particularly fast.
This solution ignores case when looking for duplicates, and it sorts the lines. The name of the file is passed in as the 1st and only argument to the batch script.
#echo off
setlocal disableDelayedExpansion
set "file=%~1"
set "sorted=%file%.sorted"
set "deduped=%file%.deduped"
::Define a variable containing a linefeed character
set LF=^
::The 2 blank lines above are critical, do not remove
sort "%file%" >"%sorted%"
>"%deduped%" (
set "prev="
for /f usebackq^ eol^=^%LF%%LF%^ delims^= %%A in ("%sorted%") do (
set "ln=%%A"
setlocal enableDelayedExpansion
if /i "!ln!" neq "!prev!" (
endlocal
(echo %%A)
set "prev=%%A"
) else endlocal
)
)
>nul move /y "%deduped%" "%file%"
del "%sorted%"
This solution is case sensitive and it leaves the lines in the original order (except for duplicates of course). Again the name of the file is passed in as the 1st and only argument.
#echo off
setlocal disableDelayedExpansion
set "file=%~1"
set "line=%file%.line"
set "deduped=%file%.deduped"
::Define a variable containing a linefeed character
set LF=^
::The 2 blank lines above are critical, do not remove
>"%deduped%" (
for /f usebackq^ eol^=^%LF%%LF%^ delims^= %%A in ("%file%") do (
set "ln=%%A"
setlocal enableDelayedExpansion
>"%line%" (echo !ln:\=\\!)
>nul findstr /xlg:"%line%" "%deduped%" || (echo !ln!)
endlocal
)
)
>nul move /y "%deduped%" "%file%"
2>nul del "%line%"
EDIT
Both solutions above strip blank lines. I didn't think blank lines were worth preserving when talking about distinct values.
I've modified both solutions to disable the FOR /F "EOL" option so that all non-blank lines are preserved, regardless what the 1st character is. The modified code sets the EOL option to a linefeed character.
New solution 2016-04-13: JSORT.BAT
You can use my JSORT.BAT hybrid JScript/batch utility to efficiently sort and remove duplicate lines with a simple one liner (plus a MOVE to overwrite the original file with the final result). JSORT is pure script that runs natively on any Windows machine from XP onward.
#jsort file.txt /u >file.txt.new
#move /y file.txt.new file.txt >nul
you may use uniq http://en.wikipedia.org/wiki/Uniq from UnxUtils http://sourceforge.net/projects/unxutils/
Some time ago I found an unexpectly simple solution, but this unfortunately only works on Windows 10: the sort command features some undocumented options that can be adopted:
/UNIQ[UE] to output only unique lines;
/C[ASE_SENSITIVE] to sort case-sensitively;
So use the following line of code to remove duplicate lines (remove /C to do that in a case-insensitive manner):
sort /C /UNIQUE "incoming.txt" /O "outgoing.txt"
This removes duplicate lines from the text in incoming.txt and provides the result in outgoing.txt. Regard that the original order is of course not going to be preserved (because, well, this is the main purpose of sort).
However, you sould use these options with care as there might be some (un)known issues with them, because there is possibly a good reason for them not to be documented (so far).
The Batch file below do what you want:
#echo off
setlocal EnableDelayedExpansion
set "prevLine="
for /F "delims=" %%a in (theFile.txt) do (
if "%%a" neq "!prevLine!" (
echo %%a
set "prevLine=%%a"
)
)
If you need a more efficient method, try this Batch-JScript hybrid script that is developed as a filter, that is, similar to Unix uniq program. Save it with .bat extension, like uniq.bat:
#if (#CodeSection == #Batch) #then
#CScript //nologo //E:JScript "%~F0" & goto :EOF
#end
var line, prevLine = "";
while ( ! WScript.Stdin.AtEndOfStream ) {
line = WScript.Stdin.ReadLine();
if ( line != prevLine ) {
WScript.Stdout.WriteLine(line);
prevLine = line;
}
}
Both programs were copied from this post.
set "file=%CD%\%1"
sort "%file%">"%file%.sorted"
del /q "%file%"
FOR /F "tokens=*" %%A IN (%file%.sorted) DO (
SETLOCAL EnableDelayedExpansion
if not [%%A]==[!LN!] (
set "ln=%%A"
echo %%A>>"%file%"
)
)
ENDLOCAL
del /q "%file%.sorted"
This should work exactly the same. That dbenham example seemed way too hardcore for me, so, tested my own solution. usage ex.: filedup.cmd filename.ext
Pure batch - 3 effective lines.
#ECHO OFF
SETLOCAL
:: remove variables starting $
FOR /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a="
FOR /f "delims=" %%a IN (q34223624.txt) DO SET $%%a=Y
(FOR /F "delims=$=" %%a In ('set $ 2^>Nul') DO ECHO %%a)>u:\resultfile.txt
GOTO :EOF
Works happily if the data does not contain characters to which batch has a sensitivity.
"q34223624.txt" because question 34223624 contained this data
1.1.1.1
1.1.1.1
1.1.1.1
1.2.1.2
1.2.1.2
1.2.1.2
1.3.1.3
1.3.1.3
1.3.1.3
on which it works perfectly.
Did come across this issue and had to resolve it myself because the use was particulate to my need.
I needed to find duplicate URL's and order of lines was relevant so it needed to be preserved. The lines of text should not contain any double quotes, should not be very long and sorting cannot be used.
Thus I did this:
setlocal enabledelayedexpansion
type nul>unique.txt
for /F "tokens=*" %%i in (list.txt) do (
find "%%i" unique.txt 1>nul
if !errorlevel! NEQ 0 (
echo %%i>>unique.txt
)
)
Auxiliary: if the text does contain double quotes then the FIND needs to use a filtered set variable as described in this post: Escape double quotes in parameter
So instead of:
find "%%i" unique.txt 1>nul
it would be more like:
set test=%%i
set test=!test:"=""!
find "!test!" unique.txt 1>nul
Thus find will look like find """what""" file and %%i will be unchanged.
I have used a fake "array" to accomplish this
#echo off
:: filter out all duplicate ip addresses
REM you file would take place of %1
set file=%1%
if [%1]==[] goto :EOF
setlocal EnableDelayedExpansion
set size=0
set cond=false
set max=0
for /F %%a IN ('type %file%') do (
if [!size!]==[0] (
set cond=true
set /a size="size+1"
set arr[!size!]=%%a
) ELSE (
call :inner
if [!cond!]==[true] (
set /a size="size+1"
set arr[!size!]=%%a&& ECHO > NUL
)
)
)
break> %file%
:: destroys old output
for /L %%b in (1,1,!size!) do echo !arr[%%b]!>> %file%
endlocal
goto :eof
:inner
for /L %%b in (1,1,!size!) do (
if "%%a" neq "!arr[%%b]!" (set cond=true) ELSE (set cond=false&&goto :break)
)
:break
the use of the label for the inner loop is something specific to cmd.exe and is the only way I have been successful nesting for loops within each other. Basically this compares each new value that is being passed as a delimiter and if there is no match then the program will add the value into memory. When it is done it will destroy the target files contents and replace them with the unique strings

Batch script .exe delete selection

There is a folder which contains some random files:
file1.txt
file2.exe
file3.cpp
file4.exe
How to SIMPLY display exe files connected with numbers like this:
1. file2.exe
2. file4.exe
And then I enter the number of the file, which I want to delete.. If it is even possible to do this simply..
Shortest bullet proof solution I can come up with. Like Anders, the DEL statement is disabled by the ECHO command. Remove the ECHO to make the menu functional.
#echo off
setlocal disableDelayedExpansion
for /f "delims==" %%A in ('set menu 2^>nul') do set "%%A="
for /f "tokens=1* delims=:" %%A in ('dir /b *.exe 2^>nul ^| findstr /n "^"') do (
set menu%%A=%%B
echo %%A. %%B
)
if not defined menu1 exit /b
set "delNum="
set /p "delNum=Delete which file (enter the number): "
setlocal enableDelayedExpansion
if defined menu!delNum! echo del "!menu%delNum%!"
The only thing I can think of that could go wrong is part of the menu could scroll off the screen if there are too many entries.
Additional messages can easily be incorporated. and an ELSE condition could be appended to the input validation to deal with invalid input.
A few subtle points of the code:
FINDSTR /N provides incrementing file number. Avoids need for delayed expansion or CALL within menu builder loop. Delayed expansion should not be enabled when expanding a FOR variable containing a file name because it will corrupt names containing !.
: is a safe FOR delimiter because a file name cannot contain :.
delNum is cleared prior to SET /P because SET /P will preserve existing value if <Enter> is pressed without entering anything.
Checking for the existence of the variable is the simplest way to validate the input. This is why it is critical that any existing MENU variables are undefined prior to building the menu.
Must use delayed expansion in IF DEFINED validation, otherwise space in input could crash the script (thanks Anders for pointing out the flaw in the original code)
DEL target must be quoted in case it contains spaces, even when delayed expansion is used.
Added test to make sure at least one menu entry exists before continuing. There may not be any .exe files left to delete.
#echo off
setlocal EnableDelayedExpansion
set i=0
for %%f in (*.exe) do (
set /A i+=1
set file[!i!]=%%f
echo !i!. %%f
)
set i=0
set /P i=File to delete:
del !file[%i%]!
Not exactly pretty but it gets the job done
#echo off
setlocal ENABLEEXTENSIONS DISABLEDELAYEDEXPANSION
goto main
:addit
set /A end=end + 1
set %end%=%~1
echo %end%. %~1
goto :EOF
:main
set end=0
for %%A in ("*.exe") do (
call :addit "%%~A"
)
if "%end%"=="0" goto :EOF
echo.&set idx=
set /P idx=Delete (1...%end%)
if not "%idx"=="" if %idx% GEQ 1 if %idx% LEQ %end% (
for /F "tokens=1,* delims==" %%A in ('set %idx% 2^>nul') do (
if "%idx%"=="%%~A" (
echo.Deleting %%~B...
rem del "%%~B"
)
)
)

Resources