how to change variable value inside loop in batch - variables

I use the below code in order to create a directory from the value of the first 4 chars of collector text file
#echo off & setlocal enabledelayedexpansion
:loop
set /P txt_file=<Collector.txt
Set collector_id=!txt_file:~0,4!
:: check for existence of [OutputFolder]
:: if [OutputFolder] doesn't exist, create it
if not exist %collector_id% (
echo folder %collector_id% not found
echo creating folder %collector_id%
md %collector_id%
)
xcopy *.txt %collector_id% /v
Del *.txt
goto loop
I want to execute the above loop continuously in order to check if current directory is empty or not. If not I want to make a dir, if does not exist, with name the first 4 chars of collector.txt.
If the directory is not empty everything is ok. When the above is looping and I add collector.txt to the current directory the collector_id does not change.
Where am I wrong?
Is there any other way, expect infinite, loop to do this?

Put setlocal EnableDelayedExpansion at the start, and use !var! instead of %var%. Then it is evaluated every time.

Related

Grouping files and 'splitting' by number and copying them inside folders

I have 5000+ files inside a directory.
I want to manage these files 'splitting' every 500 files so first pack is copied inside folder1, pack2 of other 500 files is copied in folder2 and so on.
Which .bat script can I use ?
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir\t w o"
SET "destdir=U:\destdir"
SET /a destcount=0
SET /a maxcount=5
SET /a filecount=maxcount
FOR /f "delims=" %%a IN (
'dir /b /a-d "%sourcedir%\*" '
) DO (
SET /a filecount +=1
IF !filecount! geq %maxcount% (
SET /a filecount=0
SET /a destcount +=1
MD "%destdir%\folder!destcount!"
)
ECHO(COPY "%sourcedir%\%%a" "%destdir%\folder!destcount!\"
)
GOTO :EOF
You would need to change the settings of sourcedir and destdir to suit your circumstances.
maxcount sets the number of files to assign to a group.
The required COPY commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(COPY to COPY to actually copy the files. Append >nul to suppress report messages (eg. 1 file copied)
Essentially, count the number of transfers and increment the destination-directoryname each time a group is complete, using delayedexpansion to access the run-time values of the counters

Removing spaces from a variable in batch

I am writing a file to remove spaces from filenames in a folder and then put the result in a .txt file. I just get a result of "Echo is on." over and over.
This is what I have so far:
#echo ON
SET LOCAL EnableDelayedExpansion
For %%# in (*.*) do (
SET var=%%~n#
Set MyVar=%var%
set MyVar=%MyVar: =%
echo %MyVar%>>text.txt
)
Can someone tell me whats wrong?
Removing all spaces (not just leading and trailing) can be done without using setlocal enabledelayedexpansionwith the following line:
set var=%var: =%
This works by replacing all spaces in the string with the empty string.
Source: DOS - String Manipulation
The reason why you are getting ECHO is on. is because delayed expansion was not used, which caused the value of %var% and %MyVar% to be inserted before the for command is run, and since they were not defined at the start, empty variables were inserted in. When the echo %MyVar%>>text.txt was run, it was interpreted as echo >>text.txt. When echo is run without any arguments, it outputs whether echo is on or off, which is what you get in text.txt.
To fix the problem, you have to do two things:
First, there is something wrong with your second line. There is no space between set and local in setlocal. The second line should be SETLOCAL EnableDelayedExpansion.
Second, to use delayed expansion, you have to replace all %s in each variable with !, like !var! instead of %var%.
End result:
#echo ON
SETLOCAL EnableDelayedExpansion
For %%# in (*.*) do (
SET var=%%~n#
Set MyVar=!var!
set MyVar=!MyVar: =!
echo !MyVar!>>text.txt
)
You actually do not need to use a temporary variable in this case, you can just do SET MyVar=%%~n# and skip to set MyVar=!MyVar: =!.
The wrong thing is you've enabled the variable expansion (you wroted it bad...) and also you are not using it, when you use enabledelayedexpansion you need to write the variable names as this: !Variable! instead of this else: %Variable%
But you don't need to use it with this code:
#echo ON
For %%# in (*) do (
SET "var=%%~n#"
Call Set "MyVar=%%var: =%%"
Call echo %%MyVar%%>>text.txt
)
Run the following batch in the folder holding the files to be renamed
#echo off
setlocal enabledelayedexpansion
for %%j in (*.*) do (
set filename=%%~nj
set filename=!filename=.=_!
set filename=!filename= =_!
if not "!filename!"=="%%~nj" ren "%%j" "!filename!%%~xj"
)
you just need to add the print to txt
The set var=%var: =% did not work for me.
So I tried with success for a number the following code:
set /a var-=1 & set /a var+=1

Batch file copying script giving errors on for loop

I'm in the middle of writing a batch script that will copy a bunch of tiny files from one location to another, verify that the file exists in the new directory, delete the original, and move on. I've implemented a FOR loop to do this, but I can't seem to get it working. Any ideas?
::Copying files-
::For loop copies file, verifies file was copied,
::and removes file from source.
for %%f in (Q:%source%\*) do (
:recopy
copy %%f %dest%\%%f
if not exist %dest%\%%f goto recopy
set /a count+=1
del %source%\%%f
echo copied !count! of %total%
ping -n 1 -w 500 1.1.1.1 >nul
)
The inputs for the variables are as follows:
set /P source=Enter path to files on P:(Temp) drive (EX: jdoe\copy)
set dest=D:Temp\Copy
Scripted adding if network share is as follows:
net use Q: \\SERVER\Temp
The error given is:
The system cannot find the file specified
and the error is repeated until the screen fills.
Full pastebin at http://pastebin.com/yjXP7H6U
You can't have a label within a for loop or if statement if memory serves. You should move :recopy outside the loop. Something like this:
::Copying files-
::For loop copies file, verifies file was copied,
::and removes file from source.
for %%I in (Q:\%source%\*) do (
call :recopy "%%~fI" "%dest%\%%~nxI"
set /a count+=1
del "%%~fI"
echo copied !count! of %total%
ping -n 1 -w 500 1.1.1.1 >nul
)
goto :EOF
:recopy source dest
copy "%~1" "%~2"
if not exist "%~2" call :recopy "%~1" "%~2"
goto :EOF

Variables in loops Dont Work, Batch

This is the new Script and it Still Doesn't Work
I Get The syntax of the command is incorrect.
on FOR /F "USEBACKQ tokens=*" %%A IN (TYPE "C:\Windows\System32\tasks\at!num! ^| FIND "Command") DO (
SETLOCAL ENABLEDELAYEDEXPANSION
set num=1
:START
IF NOT EXIST "C:\Windows\System32\tasks\at%num%" (GOTO:EOF)
FOR /F "USEBACKQ tokens=*" %%A IN (`TYPE "C:\Windows\System32\tasks\at!num! ^| FIND "Command"`) DO (
set var=%%A
ECHO %var%
SET /a num=%num%+1
PAUSE
)
GOTO:START
To understand your code, I'm going to break it down into logic first then try to solve it. Let me know if I miss a detail...
Set num var to 0
Begin :Loop
set num var to its current value ::NOT NEEDED - You've specified this prior to the GOTO
increment num var by +1
if myfolder\at* file exists then read at%num% and find a string then output that line to %tmp%\1.txt ::Need quotations on file location.
set F var to the line stored in %tmp%\1.txt
set F="%%F: =%%" ::Please explain what you are trying to do with this command.
set F to start on 10th character and remove the last 11 characters from the line.
echo the variable
If it doesn't exist, exit, but if it does return to :Loop
You should tell us what you are attempting. If it is as simple as saving a variable from a text file output, set F=<file.txt will work. If it didn't, then something happened prior to that command. Still... what is set F="%%F: =%%"?
Unless you are using a FOR loop variable, there is no need to use %% on each end of the variable.
If this were a FOR loop, it would look like this:
SETLOCAL ENABLEDELAYEDEXPANSION
set num=1
:START
IF NOT EXIST "myFolder\at%num%.txt" (GOTO:EOF)
FOR /F "USEBACKQ tokens=*" %%A IN (`TYPE "myFolder\at%num%.txt" ^| FIND /i "string"`) DO (
PAUSE
SET var=%%A
ECHO !var!
PAUSE
SET var=!var: =!
ECHO !var!
PAUSE
SET var=!var:~10,-11!
ECHO !var!
PAUSE
SET /a num=!num!+1
ECHO !num!
PAUSE
)
GOTO:START
One good practice to check if commands are working, such as SET, insert an ECHO on the variable and a PAUSE right after each time you believe the variable should be changed. This will track what has changed on the variable so you can see if your command was correct and the changes were made.
I'd suggest using Batch's inbuilt function for loops, see here.
Conditionally perform a command for a range of numbers
Syntax
FOR /L %%parameter IN (start,step,end) DO command
Or maybe iterating over files in a folder would be better for what you are trying to do?
Loop through files (Recurse subfolders)
Syntax
FOR /R [[drive:]path] %%parameter IN (set) DO command
Or iterating over file contents?
Loop command: against a set of files - conditionally perform
a command against each item.
Syntax
FOR /F ["options"] %%parameter IN (filenameset) DO command
FOR /F ["options"] %%parameter IN ("Text string to process") DO command
This site has plenty of examples here which should point you in the right direction.
There are a few issues with your code, I've amended as follows to get the variable populated with the contents of the temp file.
set num=0
:Loop
set /a num=%num%+1
if exist "myFolder\at*" (
TYPE "myFolder\at%num%" | FINDSTR "\<Command\>" > "%temp%\1.txt"
set /P F=<"%TEMP%\1.txt"
Echo %F%
Pause
)
I don't know if this is the problem, but have you tried enabling:
setlocal enabledelayedexpansion
Then, inside the loop (or the IF(...)), you use !foo! to signify environment variables instead of %foo%.
See setlocal /? and set /? for more information.

How can I count how many calls of a cmd file?

How can I count how many calls of a cmd file?
I'm struggling with something like this but it didn't work:
#IF NOT EXIST Calls.log echo. > Calls.log
#for %%i in (Calls.log) do set size=%%~zi
#IF %size% EQU 0 (
#ECHO 1 > Calls.log
) ELSE (
#set /p v=<Calls.log
#set /A v+=1
#echo %v% > Calls.log
)
If all you're trying to do is count how many times a cmd script is called, you can just append one character to a file every time it runs rather than fiddling around with expression evaluation every time the script is run. This also has the advantage of making the script quicker since the analysis of the count is moved elsewhere.
The counter file expands by one byte every time, so watch out if you're calling it a truly large number of times since the file will expand. But even, calling it once per second, a 1G file will accrue only after 30 years.
At the top of your script, just put:
set >>countfile.txt <nul: /p x=X
This simply adds the character X to the end of the countfile.txt file every time the script is called. It uses the "set/p" command with input/output redirection, which is the only way I'm aware of to get a character out without a CR/LF following it (like the UNIX "echo -n").
To get a count of the number of calls to date, you can use the file size environment variable modifier, as in the following script (I expect this will be done less often than running the script so it's better to put the grunt work here [in fact, it's not a lot of grunt work since it's not counting the characters, rather it gets the information directly from the directory entry]):
#echo off
goto :main
:getsize
echo %~z1
goto :eof
:main
setlocal enableextensions enabledelayedexpansion
call :getsize countfile.txt
endlocal
To reset the count, use the following extremely complicated command (I'm thinking of patenting this):
del countfile.txt
One other thing I'd suggest - you don't need to prefix every command with "#" to prevent echo, you can simply put "#echo off" at the top of your script for global no-echo. If you want to selectively echo some commands, just ignore this paragraph.
The complete if block is parsed at once and thus all environment variables in it are getting replaced by their values at the time before the if block gets executes. You need to enable delayed variable expansion and use !v!:
#setlocal enabledelayedexpansion
#IF NOT EXIST Calls.log echo. > Calls.log
#for %%i in (Calls.log) do set size=%%~zi
#IF %size% EQU 0 (
#ECHO 1 > Calls.log
) ELSE (
#set /p v=<Calls.log
#set /A v+=1
#echo !v! > Calls.log
)
And you can simplify the code as follows:
#echo off
setlocal enabledelayedexpansion
IF NOT EXIST Calls.log (
ECHO 1 > Calls.log
) ELSE (
set /p v=<Calls.log
set /A v+=1
echo !v! > Calls.log
)
There is no need to create the file beforehand (and even that I'd solve with copy nul Calls.log, since that ensures a file size of 0).
The following code works on my computer:
#if not exist Calls.log (
echo 0 > Calls.log
)
#set /p v=< Calls.log
#set /a v=v+1
echo %v% > Calls.log