Manipulation on delayed expansion string variable is failing - string

I am trying to find a particular line from an XML file and extract the value using string manipulation operations.
Below is the code I am trying.
#echo off
setlocal enabledelayedexpansion
::Expected line is "<filename>c:\temp\file1</filename>"
for /f "tokens=*" %%i in ('findstr /i "filename" file1.props') do (
SET LINE=%%i
)
echo !LINE!
SET FILENAME=!LINE:<filename>=!
SET FILENAME=%FILENAME:</filename>=%
ECHO !FILENAME!
And the output is:
<filename>c:\temp\file1</filename>
The system cannot find the file specified.
ECHO is off.
I actually want this value c:\temp\file1
Someone please help me correct the code or please suggest any other simpler way.

The problem is the execution of set. The parser interprets the > and < as redirection, so it will fail with a syntax error. Use quotes to process it as intended (`set "var=value"):
#echo off
setlocal enabledelayedexpansion
REM echo ^<filename^>c:\temp\file1^</filename^>>file1.props
::Expected line is "<filename>c:\temp\file1</filename>"
for /f "tokens=*" %%i in ('findstr /i "filename" file1.props') do (
SET "LINE=%%i"
)
echo !LINE!
SET "FILENAME=!LINE:<filename>=!"
SET "FILENAME=%FILENAME:</filename>=%"
ECHO !FILENAME!
Output is:
<filename>c:\temp\file1</filename>
c:\temp\file1

Related

How can I reverse a string in Batch?

I found this solution for reversing strings that worked before, but not any more for some reason:
setlocal enabledelayedexpansion
set num=0
:LOOP
call set tmpa=%%advanced:~%num%,1%%%
set /a num+=1
if not "%tmpa%" equ "" (
set string1=%tmpa%%string1%
goto LOOP
)
My message that I receive is:
The input line is too long.
The syntax of the command is incorrect.
I simply need to reverse the string in the variable %advanced% and output it to %string1%.
If reversing strings can be done in one line, that would be super helpful in the project I am working on. If it can be done without the setlocal enabledelayedexpansion, that would be even more helpful but I doubt it is be possible.
Another way using a BAT/VBS :
#echo off
set "advanced=1234567890"
echo WScript.Echo StrReverse("%advanced%"^) >reverse.vbs
for /f "delims=" %%a in ('cscript //nologo reverse.vbs') do set "$reversed=%%a"
>nul del reverse.vbs
echo reversed string --^> %$reversed%
You said it first worked and later not anymore; I think simply clearing variable string1 will do the trick. Your code should work as is.
Next, you do not need to enable delayed expansion as you are not using it (!! expansion) anyway.
Finally, instead of asking whether tmpa is empty, you could query whether it is defined (but this is a matter of taste though).
set string1=
set num=0
:LOOP
call set tmpa=%%advanced:~%num%,1%%%
set /a num+=1
if defined tmpa (
set string1=%tmpa%%string1%
goto :LOOP
)
In this way it works if you change to set string1=!tmpa!!string1!
#echo off
setlocal enabledelayedexpansion
set "advanced=abcdefghijklmnopqrstuvwxyz!"
set "num=0"
:LOOP
call set "tmpa=%%advanced:~%num%,1%%%"
set /a num+=1
if not "%tmpa%" equ "" (
set "string1=!tmpa!!string1!"
goto LOOP
)
echo !string1!
endlocal
Another way a bit faster:
#echo off
setlocal enabledelayedexpansion
set "advanced=abcdefghijklmnopqrstuvwxyz"
echo %advanced%>"%tmp%\alpha.tmp"
for %%l in ("%tmp%\alpha.tmp") do set /a len=%%~zl
set /a len-=2
set "reverse="
set "char="
for /l %%i in (0,1,%len%) do (
for /f "usebackq" %%a in ("%tmp%\alpha.tmp") do (
set "char=%%a"
set "reverse=!char:~%%i,1!!reverse!"
)
)
del "%tmp%\alpha.tmp"
echo !reverse!
endlocal
To reverse a string or file contents:
REM eg. set string/content to file
set /p="Hello, world!"> test
certutil -encodehex -f test temp 4
REM reverse file contents
set rev=
(for /f "delims=" %i in (temp) do for %j in (%i) do set rev=%j !rev!)
set /p="%rev:~0,-6%">temp
certutil -decodehex temp out.txt
REM view content
more out.txt
Tested in Win 10 CMD

BATCH CMD - Read INI file with specialcharacter

I'm reading a config.ini file and i want to use KEY as a Variable name with VALUE as VALUE.
Config.ini
fbdestination=I:\WZPDA\workingfolder\stored
emailreport=xxx#xxxx.xxx
gmailudpw=USERNAME:PASSWORD
Im using:
FOR /F "tokens=1,2 delims=^=" %%A IN (config.ini) DO (SET %%A=%%B)
Everything works well, but I have a problem with a complex password like:
myusername:!myp4ssw0rd!
Where if I try to ECHO $gmailudpw$ I only have :
myusername:
Is there a way to read !myp4ssw0rd! as a string and not as a variable ?
Thank you
Try like this :
#echo off
setlocal disabledelayedexpansion
FOR /F "tokens=*" %%A IN ('type "config.ini"') DO SET %%A
echo %fbdestination%
echo %emailreport%
echo %gmailudpw%

Batch Script - Find words that contain a certain string withing a file

I have a file with a lot of text.
EG
Hello
This is my file
this is the end of the file
I need a script that will search the file and pull out all words (just the words and not the line into another file) that contain for example the letter e
In this case the new file would look like
Hello
file
the
end
the
file
It may also need to search for as another example bh. (including the full stop) so a file with the following
hello
bh.ah1
my file
the end
would produce a file with
bh.ah1
hope this is enough detail
#ECHO OFF
SETLOCAL
SET "target=%~1"
FOR /f "delims=" %%a IN (q22560073.txt) DO CALL :findem %%a
GOTO :EOF
:findem
SET candidate=%1
IF NOT DEFINED candidate GOTO :EOF
ECHO %1|FIND /i "%target%" >NUL
IF NOT ERRORLEVEL 1 ECHO(%1
shift
GOTO findem
I used a file named q22560073.txt for my testing.
To find the text string, use
thisbatch text
so
thisbatch e
would find the first list and
thisbatch bh.
the second.
(I combined both sample testfiles as q22560073.txt)
the /i in the find command makes the test case-insensitive.
To output to a file, simply use
thisbatch text >"filename"
where the "rabbits ears" are only required if the filenames contains spaces and other problematic characters, but do no harm in any case.
This should work for a target of any alphabetic or numeric combination plus full stop. It will not work with characters that have a special meaning to cmd.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "target=%~1"
FOR /f "delims=" %%a IN (q22560073.txt) DO (
SET "line=%%a"
SET "line=!line:(= !"
SET "line=!line:)= !"
CALL :findem !line!
)
GOTO :EOF
:findem
SET candidate=%1
IF NOT DEFINED candidate GOTO :EOF
ECHO %1|FIND /i "%target%" >NUL
IF NOT ERRORLEVEL 1 ECHO(%1
shift
GOTO findem
revised on further information.
#echo off
set "searchfor=bh."
for /f "delims=" %%i in (t.t) do (
for %%j in (%%i) do (
echo %%j|find "%searchfor%" >nul && echo %%j
)
)
for every line (%%i) do
for every word in this line (%%j) do
if searchstring found then echo word
EDIT to your comment: replace the ( with a space in the line, before processing words
#echo off
setlocal enabledelayedexpansion
set "searchfor=bh."
for /f "delims=" %%i in (t.t) do (
set t=%%i
set t=!t:(= !
for %%j in (!t!) do (
echo %%j|find "%searchfor%" >nul && echo %%j
)
)
You can do this for more characters with additional lines like set t=!t:(= ! (replace ( with )

A Batch file to read a file and replace a string with a new one

I want to create a batch file to read every line of a file in a loop and replace a string with another one. Following is my code snippet:
for /F "tokens=*" %%i in (myfile) do (
set str=%%i
set str=%str: %oldstring% = %newstring%%
echo %str% >> newfile
)
This results in a newfile with 'Echo is off' as many lines as there are in myfile. Seems like str variable holds no value at all when assigned to %%i. Can someone help me?
Try out this small script:
#echo off
set val=50
echo %val%
for /l %%i in (1,1,1) do (
set val=%%i
echo %val%
)
echo %val%
pause>nul
The output is:
50
50
1
Not what you expected, right?
That's because in a for loop, variables aren't updated until the loop has finished. To combat this, you can use setlocal enabledelayedexpansion, and replace the percent signs (%) with an exclamation mark (!):
#echo off
setlocal enabledelayedexpansion
set val=50
echo %val%
for /l %%i in (1,1,1,) do (
set val=%%i
echo !val!
)
echo %val%
pause>nul
The output:
50
1
1
The reason the str variable holds no value (during the for loop) is because it hasn't been set beforehand.
So, with these quick modifications, your script will work...
setlocal enabledelayedexpansion
for /f "tokens=*" %%i in (myfile) do (
set str=%%i
set str=!str: %oldstring% = %newstring%!
echo !str! >> newfile
)
By the way, this snippet is assuming that oldstring and newstring won't be set within the forloop, otherwise things will get messy.
Have fun.
having spent some time at this I got the correct way:
#echo off
setlocal enabledelayedexpansion
set oldstring=AF-07295
set /a count=1000
for %%f in (*.*) do (
set /a count=!count!+1
for /f "tokens=*" %%i in (%%f) do (
set str=%%i
call set str=%%str:!oldstring!=!count!%%
echo !str! >> %%~nf.ordnew
)
)
endlocal
setlocal ENABLEDELAYEDEXPANSION
set filein="c:\program files\test1.txt"
set fileout="c:\program files\test2.txt"
set old=#VERSION#
set new=2.0.3
for /f "tokens=* delims=¶" %%i in ( '"type %filein%"') do (
set str=%%i
set str=!str:%old%=%new%!
echo !str! >> %fileout%
)
working perfect
and isn't removing white spaces at the begining of the lines file

Write batch variable into specific line in a text file

I have a batch file where I need to write a variable into a specific line of a text file and override what is all ready in that line. I have the code to read specific lines from the file maybe I could switch it around to also write?
Reading lines code:
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (variables.txt) do (
set /a N+=1
set v!N!=%%a
)
set variable1=!v1!
set variable2=!v2!
set variable3=!v3!
set variable4=!v4!
I've tried to add echo %variable1% > !v4! something like that but it doesn't work.
I figured it out!! Here is the code for anyone else who might ever need it.
#echo off
setlocal enableextensions enabledelayedexpansion
set inputfile=variables.txt
set tempfile=%random%-%random%.tmp
copy /y nul %tempfile%
set line=0
for /f "delims=" %%l in (%inputfile%) do (
set /a line+=1
if !line!==4 (
echo WORDS YOU REPLACE IT WITH>>%tempfile%
) else (
echo %%l>>%tempfile%
)
)
del %inputfile%
ren %tempfile% %inputfile%
endlocal
Another option might be to overwrite the file entirely. Here's the part to do that:
:saveVars
(
ECHO %v1%
ECHO %v2%
ECHO %v3%
ECHO %v4%
ECHO %v5%
) >variables.txt
GOTO :EOF
That is, if the number of lines is fixed and known beforehand. If not, you might want to store the last value of the increment in your example code and, when saving the variables, use it like this:
:saveVars
SETLOCAL EnableDelayedExpansion
(
FOR /L %%i IN (1,1,%N%) DO (ECHO !v%%i!)
) >variables.txt
ENDLOCAL
GOTO :EOF
I'm assuming here that the v1/v2 etc. variables would be used only for synchronising with the file: when it is read, the lines are stored in those variables, and when any of them (variables) gets changed, you just call the saveVars subroutine immediately. Here's an example how you would use it:
…
SET v2=something
CALL :saveVars
…
SET v4=%somevar%
CALL :saveVars
…
If the file is small, the rewriting should be fast enough.
Not absolutely sure I've understood everything correctly, but if you want to substitute something for an existing part of a text file with a batch script, you'll need to write everything (including the changed part) to a new file first, then delete the original and rename the new file to the original name.
I can't really see a point of reading everything into variables, unless I'm missing something. You could simply iterate over the lines writing them one by one into the new file and replacing the specific line's contents with the substitute text along the way:
setLocal EnableDelayedExpansion
>newFile.txt (
for /f "tokens=* delims= " %%a in (variables.txt) do (
set /a N+=1
if !N! == 4 (ECHO substitute text) ELSE ECHO %%a
)
)
del variables.txt
rename newFile.txt variables.txt
If the substitute text must, in turn, be derived from one of the lines, you could do something like this:
setLocal EnableDelayedExpansion
>newFile.txt (
for /f "tokens=* delims= " %%a in (variables.txt) do (
set /a N+=1
if !N! == 1 SET subst_text=%%a
if !N! == 4 (ECHO !subst_text!) ELSE ECHO %%a
)
)
del variables.txt
rename newFile.txt variables.txt

Resources