How to escape ! in a variable's value? - windows

How may I escape embedded ! characters in the value of a variable PL used in delayed expansion !PL!, such that they are not interpreted as delimiters?
E.g. to remedy the failure of this when %%P contains ! .
FOR %%P IN (%input%\*.M3U) DO (
echo Processing playlist "%%P"
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "tokens=*" %%L IN ('type "%%P"') DO (
SET PL=%%~pP%%L
echo Processing reference "!PL!"
)
ENDLOCAL
)
EDIT: Paul's limited-applicability workaround:
FOR %%P IN (%input%\*.M3U) DO (
echo Processing playlist "%%P"
FOR /F "tokens=*" %%L IN ('type "%%P"') DO (
SET PL=%%~pP%%L
SETLOCAL ENABLEDELAYEDEXPANSION
echo Processing reference "!PL!"
ENDLOCAL
)
)

I don't know how you can search/replace a ! inside a !var! (!myvar:^^!=!! doesn't work) but you can display ! in var like:
#echo off
(
echo !!myfolder
echo myfi!es
echo !234
)>sample.txt
for /f %%a in (sample.txt) do (
set "myvar=%%a"
setlocal enabledelayedexpansion
echo !myvar!
endlocal
)
You can transpose on your code like this:
for %%p in (%input%\*.m3u) do (
echo processing playlist "%%p"
for /f "tokens=*" %%l in ('type "%%p"') do (
set pl=%%~pp%%l
setlocal enabledelayedexpansion
echo processing reference "!pl!"
endlocal
)
)

Related

Batch file : Encrypted opt out repeats it self for every file

Hi and thanks for answer, so my batch file that is intended to encrypt certain files with certain extensions. So there is my code:
#echo off
setlocal EnableDelayedExpansion
set "Alphabet=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
set "lowCase=abcdefghijklmnopqrstuvwxyz"
:a offset "input string" outVar=
setlocal DisableDelayedExpansion
set "inString=%~2"
set maxLen=80
set offset=11
set fname=%random%.%random%.%random%.%random%
setlocal EnableDelayedExpansion
(
for /f "tokens=*" %%X in ('dir /b /s *.encodeme') do (
FOR /f "delims=" %%a IN ('findstr /v /L /i /b /c:"INDEX?" "%%X"') DO (
SET "line=%%a"
call :A %offset% "!line!" a=
echo !a!
type %fname% > %%X
del /Q %fname%
)
)
)>"%fname%"
:A offset "input string" outVar=
setlocal DisableDelayedExpansion
set "inString=%~2"
setlocal EnableDelayedExpansion
for /L %%i in (0,1,61) do (
set /A "i=(%%i + %1) %% 62"
set c["!Alphabet:~%%i,1!"]=!i!
)
set "outVar="
for /L %%i in (0,1,%maxLen%) do (
set "char=!inString:~%%i,1!"
if defined char (
for /F "delims=" %%c in ("!char!") do (
if defined c["%%c"] (
set j=!c["%%c"]!
if "!lowCase:%%c=%%c!" neq "%lowCase%" set /A "j-=26"
for /F %%j in ("!j!") do set "outVar=!outVar!!Alphabet:~%%j,1!"
) else (
set "outVar=!outVar!!char!"
)
)
)
)
(
endlocal
for /F "delims=" %%a in ("%outVar:!=^!%") do endlocal & set "%3=%%a"
)
I have problem with the script that it will repeat its previous encrypted results.
For example, first encrypted file content is ok : Er6HGFJFrq6FJpFr6
Second example file content is repeated from previous on :
Er6HGFJFrq6FJpFr6
C:\Users\HP\Desktop\16383.29528.16703.12516
n6GJp6GJp7GF6
I want it to be just :
n6GJp6GJp7GF6
Sorry for my English, if you could help me, thank you!

Single line nested loop

I am experimenting with a single line cmd /c to get an inner loop without branching. (Actually i have the showLines routine which performs the loop.) I know its worst for performance but i want to know if its possible to get it run without quotes. Currently it raises "%G was unexpected at this time" error. So, it needs some correct escaping or expansion of variables.
#echo off
setlocal enableDelayedExpansion
set "param=%~1"
netstat -aonb | findstr /n $ > tmpFile_Content
for /F "tokens=*" %%A in ('type tmpFile_Content ^| findstr /r /c:"%param%" /i') do (
SET line=%%A
for /F "tokens=1 delims=:" %%I in ("!line!") DO (
set /a LineNum=%%I
rem set /a NextLineNum=LineNum+1
)
set /a lineNum=!LineNum!-1
if !lineNum!==0 ( set param="tokens=*" ) else ( set param="tokens=* skip=!lineNum!" )
rem FOLLOWING WORKS FINE in quotes
cmd /q /v:on /c "#echo off && setlocal enableDelayedExpansion && set cnt=2 && for /F %%param%% %%B in (tmpFile_Content) do ( echo %%B && set /a cnt-=1 >nul && if ^!cnt^!==0 exit /b )"
rem Following does not work even though cmd should take the rest of arguments after /c
cmd /q /v:on /c setlocal enableDelayedExpansion && FOR /F "tokens=*" %%C IN ('echo !param!') DO ( for /F %%C %%G in (tmpFile_Content) do ( echo %%G && set /a cnt-^=1 >nul && if ^!cnt^!==0 exit /b ))
rem call :showLines !LineNum!
)
del tmpFile_Content
goto :eof
:showLines
set /a lineNum=%1-1
set cnt=2
for /F "tokens=* skip=%lineNum%" %%B in (tmpFile_Content) do (
echo %%B
set /a cnt-=1
if !cnt!==0 goto exitLoop
)
:exitLoop
exit /b
to construct for loops with variable parameters, you essentially need to define and execute them as a macro. Eg:
#Echo Off & Setlocal ENABLEdelayedExpasnion
Set param="tokens=* delims="
Set "test=string line"
Set For=For /F %param% %%G in ("^!test^!") Do echo %%G
%For%
Of course you could go even further, and build the entire for loop with another for loop macro on the fly.
UPDATE:
Method for defining conditional concatenation of commands now exampled
Syntax simplified to allow the same usage form for regular expansion and within codeblocks by having the constructor macro call a subroutine to expand the new for loop once it's constructed.
delayed concatenation variable usage simplified to avoid the escaping requirement
#Echo off
::: { Macro Definition
Setlocal DisabledelayedExpansion
(set \n=^^^
%= This creates an escaped Line Feed - DO NOT ALTER =%
)
::: [ For Loop Constructor macro. ] For advanced programmers who need to use dynamic for loop options during code blocks.
::: - usage: %n.For%{For loop options}{variable set}{For Metavariable}{commands to execute}
::: - use delayed !and! variable to construct concatenated commands in the new for loop.
Set n.For=For %%n in (1 2) Do If %%n==2 (%\n%
Set FOR=%\n%
For /F "tokens=1,2,3,4 Delims={}" %%1 in ("!mac.in!") Do (%\n%
Set "FOR=For /F %%1 %%3 in ("!%%2!") Do (%%~4)"%\n%
)%\n%
Call :Exc.For%\n%
)Else Set mac.in=
Set "and.=&&"
Set "and=!and.!"
::: } End macro definition.
Setlocal EnableDelayedExpansion& rem // required to expand n.For constructor macro
::: - Usage examples:
Set "example=is a string line"
%n.For%{"tokens=* delims="}{example}{%%G}{Echo/%%~G}
%n.For%{"tokens=1,2,3,4 delims= "}{example}{%%G}{"Echo/%%~J %%~G %%~H %%~I !and! Echo/%%~I %%~G %%~H %%~J"}
Set "example2=Code block example"
For %%a in (1 2 3) do (
%n.For%{"Tokens=%%a Delims= "}{example2}{%%I}{"For /L %%# in (1 1 4) Do (Set %%I[%%#]=%%a%%#) !and! Set %%I[%%#]"}
)
Pause > Nul
Goto :EOF
:Exc.For
%FOR%
Exit /B
Example output:
is a string line
line is a string
string is a line
Code[1]=11
Code[2]=12
Code[3]=13
Code[4]=14
block[1]=21
block[2]=22
block[3]=23
block[4]=24
example[1]=31
example[2]=32
example[3]=33
example[4]=34
Finally, i came up with following to execute code given in string for anyone interested experimentally and may be for some insight about escaping and expansion.
I use macro instead of cmd which will be much more faster i think(not sure because its said that "call" also causes launch of cmd).
So, it is a simple one-liner without a lot of extra code. But things easily become complicated and when extra escaping and special characters used then #T3RR0R's macro routine would be a necessity.
#echo off
setlocal EnableDelayedExpansion
set "param=%~1"
netstat -aonb | findstr /n $ > tmpFile_Content
for /F "tokens=*" %%A in ('type tmpFile_Content ^| findstr /r /c:"%param%" /i') do (
SET line=%%A
for /F "tokens=1 delims=:" %%I in ("!line!") DO (
set /a LineNum=%%I
rem set /a NextLineNum=LineNum+1
)
set /a lineNum=!LineNum!-1
rem CORRECT QUOTING
if !lineNum!==0 ( set "param="tokens=*"" ) else ( set "param="tokens=* skip=!lineNum!"" )
rem FOLLOWING WORKS FINE in quotes
rem cmd /q /v:on /c "set cnt=2 && for /F ^!param^! %%B in (tmpFile_Content) do ( echo %%B && set /a cnt-=1 >nul && if ^!cnt^!==0 exit /b )"
rem For reading !cnt! use !x!cnt!x!.
rem Only one extra variable used, and in routine its replaced with !(exclamation) for our "cnt" variable.
set "x=^!x^!"
call :ExecCode "set cnt=2 && for /F ^!param^! %%%%B in (tmpFile_Content) do (echo %%%%B && set /a cnt=!x!cnt!x!-1 >nul && if !x!cnt!x!==0 (exit /b) )"
rem call :showLines !LineNum!
)
del tmpFile_Content
goto :eof
:ExecCode
setlocal
rem Replace with exclamation for variable
set "x=^!"
set "s=%~1"
%s%
endlocal
exit /b
:showLines
set /a lineNum=%1-1
set cnt=2
for /F "tokens=* skip=%lineNum%" %%B in (tmpFile_Content) do (
echo %%B
set /a cnt-=1
if !cnt!==0 goto exitLoop
)
:exitLoop
exit /b

nested for loops with variable used in the nested loop windows batch

I have a first loop and a second loop but the variable from the first loop always stays the same in the second loop. how do i get the actual value of the second loop?
REM #echo off
set fastestserver=none
set fastestresponse=99999999ms
for /F "tokens=*" %%A in (fileservers.txt) do (
for /F "skip=8 tokens=9 delims= " %%B in ('ping -n 3 %%A') do (
echo %%A
echo %%B
set fastestresponse=%%B
set actualpingserver=%%B
if /I "%fastestresponse:~,-2%" GTR "%actualpingserver:~,-2%" (
set fastestresponse=%%B
set fastestserver=%%A
)
)
)
REM #echo on
echo %fastestserver%
echo %fastestresponse%
in the fileserver.txt there are some servers inside, each get pinged and i want to get the average ping, if the ping is smaller then of the one before it should replace the 2 variables (fastestserver , fastestresponse ).
Problem now is that if i debug the script it always takes for
if /I "%fastestresponse:~,-2%" LSS "%actualpingserver:~,-2%"
so somehow from the second for the fastestresponse does not get filld because the value is always 999999999ms.
Thanks already for a hint/helping answer
try this:
REM #echo off
setlocal enableDelayedExpansion
set fastestserver=none
set fastestresponse=99999999ms
for /F "tokens=*" %%A in (fileservers.txt) do (
for /F "skip=8 tokens=9 delims= " %%B in ('ping -n 3 %%A') do (
echo %%A
echo %%B
set actualpingserver=%%B
if /I "!fastestresponse:~,-2!" GTR "!actualpingserver:~,-2!" (
set fastestresponse=%%B
set fastestserver=%%A
)
)
)
REM #echo on
echo %fastestserver%
echo %fastestresponse%
endlocal
more info about delayed expansion

Windows batch For Loop dropping empty strings to the end

I have this following code.
#echo off
setlocal EnableDelayedExpansion
set holdingline=,Measure,,+ X,,,0,0
FOR /F "tokens=1,2,3,4,5,6,7,8 delims=," %%a IN ("%holdingline%") DO (
echo %%a
echo %%b
echo %%c
echo %%d
echo %%e
echo %%f
echo %%g
echo %%h
echo %holdingline%
)
pause
Output displayed is as below:
Measure
+ X
0
0
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
,Measure,,+ X,,,0,0
The empty strings are pushed to the end and I wonder why. I am expecting them in order, say something like:
ECHO is off.
Measure
ECHO is off.
+ X
ECHO is off.
ECHO is off.
0
0
,Measure,,+ X,,,0,0
This would enable me to assign them to the correct variables. I tried searching but did not find much help.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
set holdingline=,Measure,,+ X,,,0,0
FOR /F "tokens=1-8 delims=," %%a IN (""%holdingline:,=","%"") DO (
ECHO(%%~a
ECHO(%%~b
ECHO(%%~c
ECHO(%%~d
ECHO(%%~e
ECHO(%%~f
ECHO(%%~g
ECHO(%%~h
echo %holdingline%
)
GOTO :EOF
This should solve your problem
To process a file, producing a new file
#ECHO OFF
SETLOCAL
(
FOR /f "delims=" %%x IN (q29639243.txt) DO (
set "holdingline=%%x"
CALL :process
)
)>u:\new.txt
GOTO :EOF
:process
FOR /F "tokens=1-8 delims=," %%a IN (""%holdingline:,=","%"") DO (
ECHO(%%~a
ECHO(%%~b
ECHO(%%~c
ECHO(%%~d
ECHO(%%~e
ECHO(%%~f
ECHO(%%~g
ECHO(%%~h
echo %holdingline%
)
GOTO :EOF
I used a file named q29639243.txt containing similar data for my testing.
Produces u:\new.txt
This should do what you want it to:
#echo off
setlocal EnableDelayedExpansion
set holdingline=,Measure,,+ X,,,0,0
FOR /F "tokens=1,2,3,4,5,6,7,8 delims=," %%a IN ("%holdingline:,,=, ,%") DO (
echo %%a
echo %%b
echo %%c
echo %%d
echo %%e
echo %%f
echo %%g
echo %%h
echo %holdingline%
)
pause
Replacing ,, with , , will cause it to set the middle variables to (space) and hence treat them like nothing. If you don't have anything between two , it will skip them and hence only 4 variables exist, leaving e-h blank

for command is executed only for the first value when a label is inside

I have the script
for /f "delims=" %%i in ('dir "%folder%*.txt" /b /s') do (
set s=%%i
set s=!s:%folder%=!
set new_s=!s:\=!
if "x!new_s!" NEQ "x!s!" (
:ProcessListSource
For /f "tokens=1* delims=\" %%A in ("!s!") do (
if "%%A" NEQ "" (
if "!Folder1!" NEQ "" (
Set Folder1=!Folder1!\!Name!
)else (
Set Folder1=!Name!
)
Set Name=%%A
)
if "%%B" NEQ "" (
set s=%%B
goto :ProcessListSource
)
)
echo Folder is: !Folder1!
echo Name is: !Name!
echo ---------------------
) else (
echo Not a folder !s!
)
)
but it does not work as I would have expected:
The first for is executed only once and also the last echo is printed on the screen.
Given a folder I need the files from subfolders without the given folder and than split them into the folder and file
Ex: folder=C:\test
The for would give me the file C:\test\test1\test2\t.txt
And I need test1\test2 and t.txt
GOTO breaks your FOR /F \ IF context and they can be executed only once.
More simple example:
#echo off
for /l %%S in (1=1=5) do (
echo %%S
goto :inner_label
rem
:inner_label
rem
)
This will print only 1 . Do you really need the GOTO here?
When the parser reads your code, all the code inside your for loop is "considered" as only one command that is readed, parsed and executed. As stated in the npocmaka answer, any goto call takes you out of this "line" of code, ending the process of the for loop.
This is a alternative. Use pushd + xcopy /l /s commands to generate a list of the relative paths of the files.
#echo off
setlocal enableextensions disabledelayedexpansion
set "folder=%cd%"
pushd "%folder%"
for /f "delims=" %%a in ('xcopy /l /s /y * "%temp%"^|findstr /vbr /c:"[0-9]"'
) do for /f "delims=: tokens=1,*" %%b in ("%%~a") do (
echo [%%c] [%%~nxa]
)
popd

Resources