I try to write some simple program in windows batch file. This program is similar to some simple application from "C programming language" Kernighan and Ritchie.
The task of this program is to count char numbers and words numbers. Belove there is a source code
rem Char Number and words number
#echo off
cls
echo ===============================================================
echo input strin
set /P a=
::set variables
set Temp_str=%a%
set /A charcounter = 0
set /A wordscounter = 0
:loop
if defined Temp_str (
set /P actual_char=%Temp_str:~0,1%
if %actual_char%=="" ( set /A wordscounter+=1 )
set Temp_str=%Temp_str:~1%
set /A charcounter+=1;
goto loop
)
echo %a% %charcounter% %wordscounter%
There is error somewher but I can't find it. I don't know what is wrong. I actually start with batch windows programming.
To debug batch files always disable #echo off otherwise you're flying blind
From there you'll see the issue is on the line
if %actual_char%=="" ( set /A wordscounter+=1 )
You need to add quotes.
if "%actual_char%"=="" ( set /A wordscounter+=1 )
In addition there are other issues with the code:
1).
set /P actual_char=%Temp_str:~0,1%
Should not have the /p option as you're not wanting to prompt the user to enter the character.
2) Your word counter should be checking for spaces in addition to the blank string and you also should check what happens with the end of the first word.
rem Char Number and words number
rem #echo off
cls
echo ===============================================================
set /P a=input string:
::set variables
set Temp_str=%a%
set /A charcounter = 0
set /A wordscounter = 0
:loop
if "%Temp_str%" NEQ "" (
set actual_char=%Temp_str:~0,1%
if "%actual_char%"==" " ( set /A wordscounter+=1 )
set Temp_str=%Temp_str:~1%
set /A charcounter+=1;
goto loop
)
REM Increment word count for the final word
if "%a%" NEQ "" ( set /A wordscounter+=1 )
echo %a% %charcounter% %wordscounter%
Related
I have a script that extracts lines such as :
THIS_IS_A_LINE:=
THIS_IS_A_LINE2:=
and outputs all of the same kind into another .txt file as:
THIS_IS_A_LINE
THIS_IS_A_LINE2
The script is the following:
set "file=%cd%/Config.mak"
set /a i=0
set "regexp=.*:=$"
setlocal enableDelayedExpansion
IF EXIST Source_List.txt del /F Source_List.txt
for /f "usebackq delims=" %%a in ("%file%") do (
set /a i+=1
call set Feature[!i!]=%%a
)
cd .. && cd ..
rem call echo.!Feature[%i%]!
for /L %%N in (1,1,%i%) do (
echo(!Feature[%%N]!|findstr /R /C:"%regexp%" >nul && (
call echo FOUND
call set /a j+=1
call set Feature_Disabled[%j%]=!Feature[%%N]:~0,-2!
call echo.!Feature_Disabled[%j%]!>>Source_List.txt
) || (
call echo NOT FOUND
)
)
endlocal
I also have another script that extracts lines such as:
THIS_IS_ANOTHER_LINE:=true
THIS_IS_ANOTHER_LINE2:=true
...
and outputs all of the same kind into another .txt file as:
THIS_IS_ANOTHER_LINE
THIS_IS_ANOTHER_LINE2
...
The script is the following:
set "file=%cd%/Config.mak"
set /a i=0
set "regexp=.*:=true$"
setlocal enableDelayedExpansion
IF EXIST Source_List2.txt del /F Source_List2.txt
for /f "usebackq delims=" %%a in ("%file%") do (
set /a i+=1
call set Feature[!i!]=%%a
)
cd .. && cd ..
rem call echo.!Feature[%i%]!
for /L %%N in (1,1,%i%) do (
echo(!Feature[%%N]!|findstr /R /C:"%regexp%" >nul && (
call echo FOUND
call set /a j+=1
call set Feature_Disabled[%j%]=!Feature[%%N]:~0,-6!
call echo.!Feature_Disabled[%j%]!>>Source_List2.txt
) || (
call echo NOT FOUND
)
)
endlocal
Nevertheless, there is a third kind of lines which contain numerical numbers (also some hexadecimal values), such as:
THIS_IS_AN_UNPROCESSED_LINE:=0xA303
THIS_IS_AN_UNPROCESSED_LINE2:=1943
THIS_IS_AN_UNPROCESSED_LINE3:=HELLO_DOOD_CAN_YOU_PARSE_ME?
So I need the way to extract as well those kind of lines into another .txt file such as:
THIS_IS_AN_UNPROCESSED_LINE:=0xA303
THIS_IS_AN_UNPROCESSED_LINE2:=1943
THIS_IS_AN_UNPROCESSED_LINE3:=HELLO_DOOD_CAN_YOU_PARSE_ME?
So basically extract lines which are not of the kind:
THIS_IS_AN_UNPROCESSED_LINE:=
or
THIS_IS_AN_UNPROCESSED_LINE:=true
but keeping both the sides of the line entry.
I know there must be some trick with the regular expression but I just can't find it out.
You have made your code much more complicated than it needs to be. There is no need to create an array of every line in the file.
If there are no other : or = before the first :=, then you can use FINDSTR to print out all lines that contain a string, followed by :=. FOR /F can capture and parse each matching line into the parts before and after :=, and then IF statements can classify the three different types of lines.
I use n> to open all three output files outside the main code block for improved performance, and then I use the &n> syntax to direct each output to the appropriate, already opened file. I use high numbered file handles to avoid problems described at Why doesn't my stderr redirection end after command finishes? And how do I fix it?.
#echo off
setlocal
set "file=Config.mak"
set /a "empty=7, true=8, unprocessed=9"
%empty%>empty.txt %true%>true.txt %unprocessed%>unprocessed.txt (
for /f "delims=:= tokens=1*" %%A in ('findstr /r "^[^:=][^:=]*:=" "%file%"') do (
if "%%B" equ "" (
>&%empty% (echo %%A)
) else if "%%B" equ "true" (
>&%true% (echo %%A)
) else (
>&%unprocessed% (echo %%A:=%%B)
)
)
)
The above will ignore lines that contain : or = before :=, and it will not work properly if the first character after := is : or =. I'm assuming that should not be a problem.
It should be relatively easy to write a very efficient solution using PowerShell, VBScript, or JScript that eliminates the limitations.
You could also use JREPL.BAT - a powerful and efficient regular expression text processing command line utility. JREPL.BAT is pure script (hybrid batch/JScrpt) that runs natively on any Windows machine from XP onward, no 3rd party exe required. And JREPL is much faster than any pure batch solution, especially if the files are large.
Here is one JREPL solution
#echo off
setlocal
set repl=^
$txt=false;^
if ($2=='') stdout.WriteLine($1);^
else if ($2=='true') stderr.WriteLine($1);^
else $txt=$0;
call jrepl "^(.+):=(.*)$" "%repl%" /jmatchq^
/f Config.mak /o unprocessed.txt >empty.txt 2>true.txt
If all you have to do is classify the lines into three different files, without worrying about stripping off the :=true and := parts for the empty and true lines, then there is a very simple pure batch solution using nothing but FINDSTR.
#echo off
set "file=Config.mak"
findstr /r ".:=$" "%file%" >empty.txt
findstr /r ".:=true$" "%file%" >true.txt
findstr /r ".:=" "%file%" | findstr /r /v ":=$ :=true$" >unprocessed.txt
I have to write a batch script that loops over files and replaces stuff. Here is a sample data from the file.
1068 1181408 META METADATA 20150618201505211
20400693 400693
30H13UC 23 00
4010 618114915
4020 3
4030 0455
4040 400
4050 0029
4070 ROck
4080 XX SMALL
4090 Worley Stone
Now I need to find the Number starting with 20 and replace the next digits frm 3rd position with 10101.
Eg: In the file the 1st number stating with 20 is the 2nd line after the line beginning with 1068.
20400693 -> 2010101
and also in 340th position in the same line.
in the same line the number in 340th positon is 400693
400693 -> 10101
This pattern may or may not occur multiple times in same file
Now I can loop over the files like
for /r %i in (*)
But how do I write out the replacement part.
#ECHO OFF
SETLOCAL
:: The directory to look for data files and to place processed files
SET "sourcedir=U:\sourcedir\t w o"
SET "destdir=U:\destdir"
:: the start of the line, and length-to-match
SET "replaceinlines=20"
SET /a lengthofmatch=2
:: Replacement text, length-to-replace, column-for secondary-replacement
SET "replaceby=10101"
SET /a replacelength=6
SET /a replacecolumn=332
:: Replace-only-if-match ?
SET "replaceifmatch=Y"
:: calculate length of second-segment-to-preserve and its start-position
SET /a seg2start=replacelength+lengthofmatch
SET /a seg2=replacecolumn-seg2start
SET /a seg3start=replacecolumn+replacelength
::
FOR /f "tokens=1*delims=" %%a IN (
'dir /b /a-d "%sourcedir%\*" '
) DO (
FOR /f "usebackqdelims=" %%x IN ("%sourcedir%\%%a") DO SET "line=%%x"&call:process
) >"%destdir%\%%a"
GOTO :EOF
:process
:: does the start-of-line match?
CALL SET "startofline=%%line:~0,%lengthofmatch%%%"
IF "%startofline%" neq "%replaceinlines%" GOTO report
:: matched start-of-line; pick up data-to-replace
CALL SET "data1=%%line:~%lengthofmatch%,%replacelength%%%"
CALL SET "data2=%%line:~%replacecolumn%,%replacelength%%%"
::
:: Not sure about this - replace-both-regardless or replace-if-data-matches
::
IF "replaceifmatch"=="Y" IF "%data1%" neq "%data2%" GOTO report
CALL SET "line=%startofline%%replaceby%%%line:~%seg2start%,%seg2%%%%replaceby%%%line:~%seg3start%%%"
:report
ECHO(%line%
GOTO :eof
You would need to change the setting of sourcedir and destdir to suit your circumstances. Produces a new file with the same filename as the source in the destination directory. U: is my test drive.
Patching your supplied data yielded the target 400693 at column 332, ot 340 as claimed.
The pattern to match at the start of the lines is placed in replaceinlines and its length in lengthofmatch
The length of the text-to-be-replaced is 6 (replacelength) but you have a replacement string of length 5.?? (replaceby)
I look at the line as havng 4 segments - the first is the 20 and the following 6 characters, the second the space between that and the second 'to be replaced' string; the last (which I named seg3 but should be seg4 is the part which follows the second 'to-be-replaced' string.
You don't say whether the replacement is to take place only if the two 'to-be-replaced' strings match or regardless, so I supplied a switch replaceifmatch - Y means "if the two match, replace both". Setting replaceifmatch to something else will replace regardless.
Beyond that, it's a simple matter of calculating the column-positions and lengths from the data provided and using call set to apply the calculated values to the strings of interest.
You can use Windows Scripting Host to get what you want.
Create a file called say, "1.wcf", and copy/paste the following:
<job>
<script language="JavaScript">
var fso = new ActiveXObject("Scripting.FileSystemObject");
var files = new Enumerator(fso.getFolder(".").files);
var count = 0;
for (; !files.atEnd(); files.moveNext())
{
var file = ""+files.item(); // make it string
if (!file.match(/.*\.txt$/))
{ continue; WScript.echo("Found itself, skipping"); }
//WScript.echo("Replacing in " + file);
var f1 = fso.OpenTextFile(file, 1);
var text = f1.ReadAll();
f1.close();
var lines = text.split("\r\n");
for (var i = 0; i < lines.length; i++)
{
var m = lines[i].match(/^20(\d+)/);
if (m)
{
lines[i] = lines[i].replace(new RegExp(m[1], "g"), '10101');
//WScript.echo("Replaced in " + lines[i]);
}
}
var f2 = fso.OpenTextFile(file, 2);
f2.Write(lines.join("\r\n"));
f2.close();
}
WScript.echo("Replaced "+count+" files");
</script>
</job>
Then, copy this file into the folder with TXT files, and run. It will process each TXT, and if a line in the TXT file starts with 20, the rest of the adjoining digits are captured into Group 1, and then are used to replace all such digit sequences on that line.
Then, the file is re-written with the updated contents.
Your spec is a bit imprecise - position of 40 string is not as stated, and you don't state whether the spacing of the replacement line matters.
Since you tagged your question with regex, I think you will be interested in my JREPL.BAT regular expression text processing utility. It is pure script (hybrid JScript/batch) that runs natively on any Windows machine from XP onward.
This first solution simply replaces the digits following 20 and 40 with the new string, disregarding original string length. So the position of the 40 string may change (does change in your example).
#echo off
for /r %%F in (*) do call jrepl "^(1068 .*\n20)\d+( +40)\d+ *$" "$110101$210101" /m f "%%F" /o -
Here is a more complicated solution that preserves the position of the 40 string (position 332 in your example)
#echo off
for /r %%F in (*) do call jrepl "^(1068 .*\n20)(\d+ +)40\d+ *$" "$1+'10101'+Array($2.length-5+1).join(' ')+4010101" /m /j /f "%%F" /o -
This final solution assumes the line is formatted with fixed width, and both the 20 and 40 numbers have maximum length of 10. This solution preserves both the position of the numbers, and the total length of the line:
#echo off
for /r %%F in (*) do jrepl jrepl "^(1068 .*\n20)\d+ *( {322}40)\d+ *$" "$110101 $210101 " /m /f "%%F" /o -
The method below assume that there are not empty lines in the files. This point may be fixed, if needed.
#echo off
setlocal EnableDelayedExpansion
rem Set working values
set "find=20"
set "replace=10101"
rem Process all files in current folder and below it
for /F "delims=" %%a in ('dir /A-D /S /B *.*') do (
rem Read this file via redirected input
rem and create a .tmp extension copy of it via redirected output
< "%%a" (
rem Read the first line
set /P "line="
set lastLine=1
rem Find the number of the lines that start with "20"
for /F "tokens=1,2 delims=: " %%b in ('findstr /N "^%find%" "%%a"') do (
rem Copy the lines before this one
set /A lines=%%b-lastLine, lastLine=%%b
for /L %%i in (1,1,!lines!) do set /P "line=!line!" & echo/
rem Process this line as desired:
rem Get the first token in this line
set "token=%%c"
rem Get the pattern to replace removing "20" from beginning of the token
rem and replace it in the entire line
for /F %%d in ("!token:*%find%=!") do set "line=!line:%%d=%replace%!"
)
rem Copy the last replaced line
echo !line!
rem Copy the rest of lines after the last replaced one
findstr "^"
) > "%%~Na.tmp"
rem Replace the original file by the processed one
move /Y "%%~Na.tmp" "%%a" > NUL
)
I'm writing a calculator on a cmd with enabled binary operations. I need to validate input data (remove letters, and other symbols that are not required for arithmetic operations)
#echo off
set data=
echo %* | findstr /R "\/\? ECHO" > nul
IF "%ERRORLEVEL%" EQU "0" goto printHelp
:main
set data= %data%%1
shift
if "%1" == "" (
echo %data% | findstr /R "^[0123456789*-+()/%!^_&|]*$" >nul 2>&1
if "%ERRORLEVEL%" EQU 0 (
echo Incorrect input data
exit /B
)
goto :result
) else (
goto :main
)
:result
set /a data="%data%"
echo %data%
exit /B
:printHelp
echo.
echo --------------------------------------------------
echo Using: calculator.bat [/?] [EXPRESSION]
echo helps you to consider arithmetic in Command Line
echo --------------------------------------------------
exit /B
My regular expression is not working. Also not considered to be a binary operation. What could be the problem?
Part 1 - Why your "regex is not working"
Your logic is wrong. FINDSTR sets ERRORLEVEL to 0 if there is a match, 1 if no match. Your regex is verifying that all characters are "valid", but your condition is treating a match as incorrect input.
Your IF statement uses quotes on one side, but not on the other. You must be consistent, otherwise it can never evaluate to TRUE.
Percent literals must be doubled within a batch script. Your regex has a percent literal that should be written as %%.
You use %ERRORLEVEL% in the same code block that sets the value. This cannot work because the value is expanded when the code block is parsed - before the value is set.
The simplest alternative is to use if errorlevel 1, which returns true if ERRORLEVEL is >= 1.
Another option is to enable delayed expansion with SETLOCAL ENABLEDELAYEDEXPANSION at top, and then use if !errorlevel! neq 0. But this would require that quoted ! literal in your regex be escaped as ^!, and ^ literal escaped as ^^.
My favorite option is to use the && and || conditional operators instead of IF.
findstr ... >nul && (match found statements) || (no match statements)
In your case, you want to take action if there was no match, so you only need the || operator.
Part 2 - Why your whole concept is not a good idea
Your validation is overly simplistic. Simply screening out invalid characters does not prevent errors. For example, 1**2 will result in an error, even though all characters are "valid". There are many other inputs with "valid" characters that would result in an error.
SET /A can work directly with environment variables. It knows how to access the value without you expanding the value in your code. This can be a powerful tool. A variable name used in a computation can include any character that is not an operator. So one can argue that there are no invalid characters for SET /A computations. Your exclusion of "invalid" characters prevents use of variables in computations.
Below is a simple batch calculator program I wrote some time ago. It is in an endless loop requesting input and displaying the result, until you enter a quit command. It supports all operators supported by SET /A.
It allows you to define and use variables in your expressions. The result of the most recent computation is always stored in a variable named #.
The calculator can display results as decimal, hexidecimal, or binary.
By default, it only displays the result of the last computation. It can be instructed to also display the value of all variables after each computation.
You can enter a command instead of a math computation. All commands begin with a \
\ Quit
\V Toggle variable listing ON or OFF
\D Decimal mode - results are displayed as decimal
\H Hex mode - results are displayed as hexidecimal
\B Binary mode - results are displayed as binary
\C X Clear variable X
\C * Clear all variables
\C X* Clear all variables that begin with X
Entering nothing will list all the currently defined variables.
Cleared variables are undefined. Note that an undefined variable has an implicit value of 0.
Here is the code:
#echo off
setlocal enableDelayedExpansion
for /f "delims==" %%v in ('set') do set %%v=
set __skip=#COMSPEC#PATHEXT#PROMPT#__mode#__str#__skip#__clr###__dispVars#
set __mode=Dec
set __dispVars=0
:top
echo:
set __str=
set /p "__str=%__mode%> "
if "!__str!"=="\" exit /b
if "!__str!"=="" call :dispVar # & call :dispVars & goto :top
if /i "!__str:~0,2!"=="\C" call :clearVars &goto :top
if /i "!__str!"=="\H" (set __mode=Hex) ^
else if /i "!__str!"=="\D" (set __mode=Dec) ^
else if /i "!__str!"=="\B" (set __mode=Bin) ^
else if /i "!__str!"=="\V" (set /a "__dispVars=^!__dispVars") ^
else set /a #=(!__str!)
call :dispVar #
if !__dispVars! gtr 0 call :dispVars
goto :top
:clearVars
for /f "delims=,; " %%v in ("!__str:~2!") do (
set __clr=%%v
if "!__clr:~-1!"=="*" (
set __clr=!__clr:~0,-1!
for /f "delims==" %%x in ('set !__clr!') do (
if "!__skip:#%%x#=!"=="!__skip!" set "%%x="
)
) else set "%%v="
)
call :dispVar #
call :dispVars
exit /b
:dispVars
setlocal
for /f "tokens=1,2 delims==" %%v in ('set') do if "!__skip:#%%v#=!"=="!__skip!" call :dispVar %%v
exit /b
:dispVar Var
setlocal
if !__mode!==Hex call :num2hex %1 disp
if !__mode!==Bin call :num2bin %1 disp
if !__mode!==Dec set /a disp=!%~1!
set var=%~1
if "!var:~0,6!"=="!var!" (
set "var=!var! ----------"
set "var=!var:~0,6!"
)
echo %var% = !disp!
exit /b
:num2hex NumVal RtnVar
setlocal enabledelayedexpansion
set hex=
set /a "dec=%~1"
set "map=0123456789ABCDEF"
for /l %%n in (1,1,8) do (
set /a "d=dec&15,dec>>=4"
for %%d in (!d!) do set "hex=!map:~%%d,1!!hex!"
)
(endlocal & rem return values
set %~2=%hex%
exit /b
)
exit /b
:num2bin NumVal RtnVar
setlocal enabledelayedexpansion
set bin=
set /a "dec=%~1"
for /l %%n in (1,1,32) do (
set /a "d=dec&1,dec>>=1"
set "bin=!d!!bin!"
)
(endlocal & rem return values
set %~2=%bin%
exit /b
)
exit /b
And here are the results of a short session:
D:\test>calculate.bat
Dec> 2*3
# ---- = 6
Dec> a=#+1
# ---- = 7
Dec>
# ---- = 7
a ---- = 7
Dec> b=(a+=5)*2
# ---- = 24
Dec> \v
# ---- = 24
a ---- = 12
b ---- = 24
Dec> c=b/3
# ---- = 8
a ---- = 12
b ---- = 24
c ---- = 8
Dec> \h
# ---- = 00000008
a ---- = 0000000C
b ---- = 00000018
c ---- = 00000008
Hex> \b
# ---- = 00000000000000000000000000001000
a ---- = 00000000000000000000000000001100
b ---- = 00000000000000000000000000011000
c ---- = 00000000000000000000000000001000
Bin> \
D:\test>
From a batch file I want to extract the number 653456 from the following string:
C:\Users\testing\AppData\Local\Test\abc123\643456\VSALBT81_COM
The number will change, however it will always be just digits.
My current theory is to search for something that fits \alldigits\, then replace the two \s with white space, but I can’t quite get it.
Assuming the number is always the parent folder (the folder before the end):
#echo off
set "str=C:\Users\testing\AppData\Local\Test\abc123\643456\VSALBT81_COM"
for %%F in ("%str%\..") do set "number=%%~nxF"
EDIT - Code sample adapted to correct errors shown in comments
set d=C:\Users\testing\AppData\Local\Test\abc123\643456\VSALBT81_COM
for %%f in ("%d:\=" "%") do for /f %%n in ('echo %%f^|findstr /b /e /r "\"[0-9]*\""') do (
echo %%~n
)
Just precede the path with a quote, split the path, replacing each backslash with a quote a space and a quote and append a quote (so we have a list of elements to iterate), and for each part check if it is formed only by numbers
#echo off
setlocal EnableDelayedExpansion
set "string=C:\Users\testing\AppData\Local\Test\abc123\643456\VSALBT81_COM"
for /L %%d in (0,1,9) do set "string=!string:\%%d=\ %%d!"
for /F "tokens=2" %%a in ("%string%") do for /F "delims=\" %%b in ("%%a") do echo Number: [%%b]
This uses a helper batch file called repl.bat from - https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat
#echo off
set "string=C:\Users\testing\AppData\Local\Test\abc123\643456\VSALBT81_COM"
echo "%string%"|repl ".*\\([0-9]*)\\.*" "$1"
Here is how I striped numbers from a string in batch (not a file path, should be generically working for a "string")
#ECHO OFF
::set mystring=Microsoft Office 64-bit Components 2013
set mystring=Microsoft 365 Apps for enterprise - en-us
echo mystring = %mystring%
for /f "tokens=1-20 delims=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!##$&*()-= " %%a in ("%mystring%") do (
IF %%a == 64 (
set ONum=%%b
GoTo varset
)
IF %%a == 32 (
set ONum=%%b
GoTo varset
)
set ONum=%%a
)
:varset
echo numfromalphanumstr = %numfromalphanumstr%
pause
https://www.dostips.com/forum/viewtopic.php?t=3499
https://superuser.com/questions/1065531/filter-only-numbers-0-9-in-output-in-classic-windows-cmd
Extract number from string in batch file
How to extract number from string in BATCH
i want to use my %variable% to manage the conditional clauses in a IF.. THEN.. ELSE in a batch file.
Something like the following:
set variable=%%homedrive%% EQU C:
if %variable% (
echo test ok
) else (
echo test fail
)
if i write on a cmd console:
set test=1 equ 1
if %test% echo OK
it works!
i'll use it in a for /f cicle:
this is my pseudo codethis is my pseudo code to correct
(
rem echo "%systemdrive%;;"
echo "%%COMPUTERNAME%% EQU [x];[some parameters1]"
echo "%%USERNAME%% NEQ [y];[some parameters2]"
echo "%%LOGONSERVER%% EQU [z];[some parameters3]"
[..]
) > "%temp%\CSG_fs.tmp"
[..]
for /f "usebackq tokens=1-2* delims=;" %%a in ("%temp%\CSG_fs.tmp") do (
set cond=%%a& set cond=!cond:~1!
set parm=%%b& set parm=!parm:~0,-1!
echo - cicle: "!cond!" --^> "!parm!"
call if !cond! call:CSG_sub_fs !parm!
echo - done
)
goto:eof
:CSG_sub_fs
[..]
goto:eof
--edit--
how can i use the variable !cond! to decide if execute the call to CSG_sub_fs?
call if !cond! call:CSG_sub_fs !parm!
does not work because it returns: "Can not find the batch label specified - IF"
and if i use
if !cond! call:CSG_sub_fs !parm!
it will say: "call:CSG_sub_fs not expected"
Well - there doesn't seem to be a question, so it's not that easy to answer.
You have a problem with
echo "^%COMPUTERNAME^% EQU [x];[some parameters1]"
because ^ does not escape % - % escapes % - use %%COMPUTERNAME%%...
(you should have been able to check this just by TYPEing "%temp%\CSG_fs.tmp"
Next problem is that
for /f "tokens=1-2* delims=; usebackq" %%a in (%temp%\CSG_fs.tmp) do (
may process the file %temp%\CSG_fs.tmp provided %temp%\CSG_fs.tmp contains no spaces, semicolons or commas. If it contains any of these deafult separators, or certain other characters with a special meaning, then you must enclose the filename in double-quotes "%temp%\CSG_fs.tmp"and use the usebackq option.
You've attempted to use usebackq but DELIMS must be the LAST option if it is used. Your code would set ";","","u","s","e","b","a","c","k" and "q" as delimiters.
Beyond that, perhaps if you explain what you intend to achieve, we'd be able to devise the appropriate code.
Try this:
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
CLS
REM I'm setting these variables for testing.
REM That isn't ususally a good idea but the SETLOCAL
REM will ensure they are restored on exit
SET computername=[x]
SET logonserver=[z]
(
rem echo "%systemdrive%;;"
echo "%%COMPUTERNAME%% EQU [x];[some parameters1]"
echo "%%USERNAME%% NEQ [y];[some parameters2]"
echo "%%LOGONSERVER%% EQU [z];[some parameters3]"
) > "%temp%\CSG_fs.tmp"
for /f "usebackqtokens=1-2* delims=;" %%a in ("%temp%\CSG_fs.tmp") do (
set cond=%%a& set "cond=IF !cond:~1! CALL :csg_sub_fs "
set parm=%%b& set parm=!parm:~0,-1!
CALL :varcmd "!cond!" "!parm!"
)
GOTO :eof
:varcmd
%~1 %~2
GOTO :eof
:csg_sub_fs
ECHO parameters supplied to csg_sub_fs were: %*
GOTO :eof
I've forced the variablenames to match the conditions you've used in order to trigger the subroutine calls. Change as you need to prove your concept.
And dont worry about imperfect English. I'm sure I wouldn't do as well in your language!