getting filename in variable & echoing them - windows

In a directory I want to get each filename into a variable and then echo the variable to the screen.
REM Example 1 works but does not put filename in variable
FOR %%F in (*.*) do (
echo %%F
)
REM Example 2 here I try to put the filename into a variable named x but when I run it it only displays the filename of
FOR %%F in (*.*) do (
set x=%%F
echo %x%
)
How can I fix this?

I think you should use delayed expansion like so
#echo off
setlocal EnableDelayedExpansion
FOR %%F in (*.*) do ( set x=%%F & echo !x! )

Related

Batch String +=? [duplicate]

I made this code
dir /B /S %RepToRead% > %FileName%
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo %z%
echo %%a
)
echo %%a is working fine but echo %z% returns "echo disabled".
I need to set a %z% because I want to split the variable like %z:~7%
Any ideas?
There are two methods to setting and using variables within for loops and parentheses scope.
setlocal enabledelayedexpansion see setlocal /? for help. This only works on XP/2000 or newer versions of Windows.
then use !variable! instead of %variable% inside the loop...
Create a batch function using batch goto labels :Label.
Example:
for /F "tokens=*" %%a in ('type %FileName%') do call :Foo %%a
goto End
:Foo
set z=%1
echo %z%
echo %1
goto :eof
:End
Batch functions are very useful mechanism.
You probably want SETLOCAL ENABLEDELAYEDEXPANSION. See https://devblogs.microsoft.com/oldnewthing/20060823-00/?p=29993 for details.
Basically: Normal %variables% are expanded right aftercmd.exe reads the command. In your case the "command" is the whole
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo %z%
echo %%a
)
loop. At that point z has no value yet, so echo %z% turns into echo. Then the loop is executed and z is set, but its value isn't used anymore.
SETLOCAL ENABLEDELAYEDEXPANSION enables an additional syntax, !variable!. This also expands variables but it only does so right before each (sub-)command is executed.
SETLOCAL ENABLEDELAYEDEXPANSION
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo !z!
echo %%a
)
This gives you the current value of z each time the echo runs.
I struggeld for many hours on this.
This is my loop to register command line vars.
Example : Register.bat /param1:value1 /param2:value2
What is does, is loop all the commandline params,
and that set the variable with the proper name to the value.
After that, you can just use
set value=!param1!
set value2=!param2!
regardless the sequence the params are given. (so called named parameters).
Note the !<>!, instead of the %<>%.
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%P IN (%*) DO (
call :processParam %%P
)
goto:End
:processParam [%1 - param]
#echo "processparam : %1"
FOR /F "tokens=1,2 delims=:" %%G IN ("%1") DO (
#echo a,b %%G %%H
set nameWithSlash=%%G
set name=!nameWithSlash:~1!
#echo n=!name!
set value=%%H
set !name!=!value!
)
goto :eof
:End
Simple example of batch code using %var%, !var!, and %%.
In this example code, focus here is that we want to capture a start time using the built in variable TIME (using time because it always changes automatically):
Code:
#echo off
setlocal enabledelayedexpansion
SET "SERVICES_LIST=MMS ARSM MMS2"
SET START=%TIME%
SET "LAST_SERVICE="
for %%A in (%SERVICES_LIST%) do (
SET START=!TIME!
CALL :SOME_FUNCTION %%A
SET "LAST_SERVICE=%%A"
ping -n 5 127.0.0.1 > NUL
SET OTHER=!START!
if !OTHER! EQU !START! (
echo !OTHER! is equal to !START! as expected
) ELSE (
echo NOTHING
)
)
ECHO Last service run was %LAST_SERVICE%
:: Function declared like this
:SOME_FUNCTION
echo Running: %1
EXIT /B 0
Comments on code:
Use enabledelayedexpansion
The first three SET lines are typical
uses of the SET command, use this most of the time.
The next line is a for loop, must use %%A for iteration, then %%B if a loop inside it
etc.. You can not use long variable names.
To access a changed variable such as the time variable, you must use !! or set with !! (have enableddelayexpansion enabled).
When looping in for loop each iteration is accessed as the %%A variable.
The code in the for loop is point out the various ways to set a variable. Looking at 'SET OTHER=!START!', if you were to change to SET OTHER=%START% you will see why !! is needed. (hint: you will see NOTHING) output.
In short !! is more likely needed inside of loops, %var% in general, %% always a for loop.
Further reading
Use the following links to determine why in more detail:
Difference between %variable% and !variable! in batch file
Variable usage in batch file
To expand on the answer I came here to get a better understanding so I wrote this that can explain it and helped me too.
It has the setlocal DisableDelayedExpansion in there so you can locally set this as you wish between the setlocal EnableDelayedExpansion and it.
#echo off
title %~nx0
for /f "tokens=*" %%A in ("Some Thing") do (
setlocal EnableDelayedExpansion
set z=%%A
echo !z! Echoing the assigned variable in setlocal scope.
echo %%A Echoing the variable in local scope.
setlocal DisableDelayedExpansion
echo !z! &rem !z! Neither of these now work, which makes sense.
echo %z% &rem ECHO is off. Neither of these now work, which makes sense.
echo %%A Echoing the variable in its local scope, will always work.
)
set list = a1-2019 a3-2018 a4-2017
setlocal enabledelayedexpansion
set backup=
set bb1=
for /d %%d in (%list%) do (
set td=%%d
set x=!td!
set y=!td!
set y=!y:~-4!
if !y! gtr !bb1! (
set bb1=!y!
set backup=!x!
)
)
rem: backup will be 2019
echo %backup%
Try this:
setlocal EnableDelayedExpansion
...
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo !z!
echo %%a
)
You can use a macro if you access a variable outside the scope
#echo off
::Define macro
set "sset=set"
for /l %%a in (1,1,4) do (
::set in loop
%sset% /a "x[%%a]=%%a*%%a"
if %%a equ 4 (
:: set in condition
%sset% "x[%%a]=x Condition"
%sset% "y=y Condition"
)
)
echo x1=%x[1]% x2=%x[2]% x3=%x[3]% x4=%x[4]% y=%y%
:: Bonus. enableDelayedExpansion used to access massive from the loop
setlocal enableDelayedExpansion
echo Echo from the loop
for /l %%a in (1,1,4) do (
::echo in one line - echo|set /p =
echo|set /p "=x%%a=!x[%%a]! "
if %%a equ 4 echo y=%y%
)
pause
I know this isn't what's asked but I benefited from this method, when trying to set a variable within a "loop". Uses an array. Alternative implementation option.
SETLOCAL ENABLEDELAYEDEXPANSION
...
set Services[0]=SERVICE1
set Services[1]=SERVICE2
set Services[2]=SERVICE3
set "i=0"
:ServicesLoop
if defined Services[%i%] (
set SERVICE=!Services[%i%]!
echo CurrentService: !SERVICE!
set /a "i+=1"
GOTO :ServicesLoop
)
The following should work:
setlocal EnableDelayedExpansion
for /F "tokens=*" %%a in ('type %FileName%') do (
set "z=%%a"
echo %z%
echo %%a
)

batch, dealing with spaces in path

I have a CSV file with leading-and-trailing doublequotes per line I want to remove, and made a DOS batch to do it. The following works for an explicit path:
#echo off
setlocal enabledelayedexpansion
for /F "tokens=*" %%A in (C:\Folder\WrappedInQuotes.csv) do (
set line=%%A
echo !line:~1,-1! >> C:\Folder\UnWrapped.csv
)
Of course, if the path has spaces in it, the following will not work:
#echo off
setlocal enabledelayedexpansion
for /F "tokens=*" %%A in (C:\Folder\Sub Folder\WrappedInQuotes.csv) do (
set line=%%A
echo !line:~1,-1! >> C:\Folder\Sub Folder\UnWrapped.csv
)
(#echo on, the message is "...cannot find the file C:\Folder\Sub", of course)
As a next-step test, I simply wrapped the two explicit filespecs in doublequotes:
#echo off
setlocal enabledelayedexpansion
for /F "tokens=*" %%A in ("C:\Folder\Sub Folder\WrappedInQuotes.csv") do (
set line=%%A
echo !line:~1,-1! >> "C:\Folder\Sub Folder\UnWrapped.csv"
)
With #echo on, the For seems to be getting the correct filespec (original CSV), but now the destination CSV has
:\Folder\Sub Folder\EachLineWrappedInQuotes.cs
(the source CSV full filespec, with first and last characters removed), instead of the contents of the source CSV with first and last characters (the doublequote wrapping) removed.
Ultimately, I want to replace the explicit paths with a path variable like %~dp0, but haven't been able to get past the "next-step test".
(I have tried to solve this by studying the many answers already given, with no success, sorry!)
To get the content of the file and remove double quotes, without the need to set variables, set usebackq
method 1:
#echo off
for /F "usebackq tokens=*" %%A in ("C:\Folder\Sub Folder\WrappedInQuotes.csv") do (
echo %%~A >> "C:\Folder\Sub Folder\UnWrapped.csv"
)
method 2, if you still want to set the variable:
#echo off
setlocal enabledelayedexpansion
for /F "usebackq tokens=*" %%A in ("C:\Folder\Sub Folder\WrappedInQuotes.csv") do (
set line=%%~A
echo !line! >> "C:\Folder\Sub Folder\UnWrapped.csv"
)
Or by using type :
#echo off
for /F "tokens=*" %%A in ('type "C:\Folder\Sub Folder\WrappedInQuotes.csv"') do (
echo %%~A >> "C:\Folder\Sub Folder\UnWrapped.csv"
)

edit variable value in a batch file using another batch

existing A.bat :
rem set variable pathVariable to appropriate value
set pathVariable=../Doc/English/MyDoc.htm
rem asd
from B.bat, I need to update the value of pathVariable with a path containing spaces, but after replacing spaces with %20 So after running B.bat, A.bat should look like :
rem set variable pathVariable to appropriate value
set pathVariable=C:/Program%20Files/XXX%20YYY/MyDoc.htm
rem asd
I tried to play with this and could write
#echo off
setlocal enabledelayedexpansion
set inputFile=A.bat
set outputFile=A_New.bat
set pathVar=../Doc/English/MyDoc.htm
set newPathVarSpace=C:/Program Files/XXX YYY/MyDoc.htm
set space=%%20
set newPathVarNoSpace=%newPathVarSpace: =!space!%
echo %newPathVarNoSpace%
for /f "tokens=1,* delims=" %%A in ( '"type %inputFile%"') do (
SET line=%%A
rem SET modified=!string:%pathVar%=%newPathVarSpace%!
SET modifiedLine=!line:%pathVar%=%newPathVarNoSpace%!
echo !modifiedLine! >> %outputFile%
)
The script works but its eating all the blank lines which I want to preserve.
Thanks for your help.
Try below piece of code -
A.BAT
rem set variable pathVariable to appropriate value.
pathVariable=C:\Test
B.BAT
#echo off
setlocal enableextensions disabledelayedexpansion
set "config=.\A.bat"
set "path=C:\Batch projects\Batch tests\bin\Debug App"
for /f "tokens=*" %%l in ('type "%config%"^&cd.^>"%config%"'
) do for /f "tokens=1 delims== " %%a in ("%%~l"
) do if /i "%%~a"=="pathVariable" (
>>"%config%" echo(pathVariable=%path%
) else (
>>"%config%" echo(%%l
)
type "%config%"
endlocal
Now go to A.BAT, Open it with Notepad and check the pathVariable Value as below -
C:\Batch projects\Batch tests\bin\Debug App

Windows batch file to find duplicates in a tree

I need a batch file ( Windows CMD is the interpreter, a .bat ) to do this type of task:
1) Search through a folder and its subfolders
2) Find files with the same filename and extension ( aka duplicates )
3) Check if they have the same size
4) If same name + same size, echo all the files except the first one ( practically I need to delete all except one copy )
Thanks for any type of help
This is only an initial script, just for check the files, in a folder and its subfolders, and their size:
#Echo off
Setlocal EnableDelayedExpansion
Set Dir=C:\NewFolder
For /r "%Dir%" %%i in (*) do (
Set FileName=%%~nxi
Set FullPath=%%i
Set Size=%%~zi
Echo "!FullPath!" - SIZE: !Size!
)
Echo.
Pause
This script does what you ask. Just set the ROOT variable at the top to point to the root of your tree.
#echo off
setlocal disableDelayedExpansion
set root="c:\test"
set "prevTest=none"
set "prevFile=none"
for /f "tokens=1-3 delims=:" %%A in (
'"(for /r "%root%" %%F in (*) do #echo %%~znxF:%%~fF:)|sort"'
) do (
set "currTest=%%A"
set "currFile=%%B:%%C"
setlocal enableDelayedExpansion
if !currTest! equ !prevTest! echo "!currFile!"
endlocal
set "prevTest=%%A"
)
But you can make the test more precise by using FC to compare the contents of the files. Also, you can incorporate the DEL command directly in the script. The script below prints out the commands that would delete the duplicate files. Remove the ECHO before the DEL command when you are ready to actually delete the files.
#echo off
setlocal disableDelayedExpansion
set root="c:\test"
set "prevTest=none"
set "prevFile=none"
for /f "tokens=1-3 delims=:" %%A in (
'"(for /r "%root%" %%F in (*) do #echo %%~znxF:%%~fF:)|sort"'
) do (
set "currTest=%%A"
set "currFile=%%B:%%C"
setlocal enableDelayedExpansion
set "match="
if !currTest! equ !prevTest! fc /b "!prevFile!" "!currFile!" >nul && set match=1
if defined match (
echo del "!currFile!"
endlocal
) else (
endlocal
set "prevTest=%%A"
set "prevFile=%%B:%%C"
)
)
Both sets of code may seem overly complicated, but it is only because I have structured the code to be robust and avoid problems that can plague simple solutions. For example, ! in file names can cause problems with FOR variables if delayed expansion is enabled, and = in file name causes a problem with npocmoka's solution.
#echo off
setlocal
for /f "tokens=1 delims==" %%# in ('set _') do (
set "%%#="
)
for /r %%a in (*.*) do (
if not defined _%%~nxa%%~za (
set "_%%~nxa%%~za=%%~fa"
) else (
echo %%~fa
)
)
endlocal

windows batch script - setting variable inside for loop

maybe i'm not representing my question clear, here's the actual code i did:
#echo off
set /p keywords="Enter keywords to search: " %=%
dir /b *.dat > filelist.txt
for /f "delims=." %%f in (filelist.txt) do (
for /f "delims= " %%g in (%%f.dat) do (
7z e %%g *sec.evtx
dir /b *.evtx > evtfile.txt
set /p tmpvar1=<evtfile.txt
del *.evtx
)
)
filelist.txt
tsnint1.dat
webint1.dat
tsnint1.dat
TSNINT1-201312091700.zip
TSNINT1-201312091600.zip
TSNINT1-201312091500.zip
TSNINT1-201312091400.zip
TSNINT1-201312091300.zip
TSNINT1-201312091200.zip
webint1.dat
WEBINT1-201312091300.zip
WEBINT1-201312091200.zip
the problem i'm facing is, evtfile consists of the right content but tmpvar1 is not assigned correctly as expected, what is my mistake and how to correct it? many thanks
You need delayed expansion to use a variable inside a block when this variable has been set (or changed) inside the same block. But you can set a variable without delayed expansion.
See this little demonstration (I used a simple if construct instead of for, but the effect is the same (not with if or for, but with blocks (inside ( and )).
#echo off
REM SETTING a variable inside a block
set "var=ONE"
echo start: %var%
if 1==1 (
echo inside block: %var%
set var=TWO
echo var has a new value:
set var
echo inside block is still old: %var%
)
echo after block: %var%
echo ----------
REM USING a variable inside a block
setlocal enabledelayedexpansion
set "var=ONE"
echo start: %var%
if 1==1 (
echo inside block: %var%
set var=TWO
echo var has a new value:
set var
echo new value inside block: !var!
echo just to demonstrate: %var%
)
echo after block: %var%
endlocal
echo ----------
echo working fine: %var%
echo not available after endlocal: !var!
This might help, using your code as a base. FWIW I hope that you have more than one copy of the .evtx files, if they are important to you.
#echo off
setocal enabledelayedexapnsion
for /f "delims=" %%f in ('dir /b *.dat') do (
for /f "delims=" %%g in ('type "%%f" ') do (
7z e "%%g" "*sec.evtx"
dir /b *.evtx > evtfile.txt
set /p tmpvar1=<evtfile.txt
echo !tempvar!
del *.evtx
)
)
One issue is that the *.evtx files are being deleted after the first archive is created, so the subsequent ones will have nothing to archive.

Resources