Replace a line with another line using IF - Batch file - windows

I am trying to replace a line in load.xml using the lines read from FileList.txt.
Contents of load.xml
<mainheader>
<InFilePath>D:\Data\All_Inputfiles\oldfile.txt</InFilePath>
</mainheader>
FileList.txt
newfile1.txt
newfile2.txt
Expecting the output with each iteration as
<mainheader>
<InFilePath>D:\Data\All_Inputfiles\newfile1.txt</InFilePath>
</mainheader>
and with the next iteration replace newfile1.txt with newfile2.txt. I am able to get original string with the final string but last part of the code is throwing syntax error, i.e. from
for /f "delims=" %%a in (!INTEXTFILE!) do call :Change "%%a" .
Could please help me?
Thanks in advance.
#echo off
SETLOCAL EnableDelayedExpansion
Set AllInputFile= D:\data\FileList.txt
SET INTEXTFILE=C:\c:\load.xml
set OUTTEXTFILE=D:\data\tmp_out.txt
SET BackupPath=D:\data\backupload.xml
Set TempFile=D:\data\tmp.txt
SET DbgFile=D:\data\debuginfo.txt
Del !TempFile!
Del !DbgFile!
Copy !INTEXTFILE! !BackupPath!
:replace
findstr /g "InFilePath" !INTEXTFILE!>!TempFile!
:: set string=" <InFilePath>D:\Data\All_Inputfiles\oldfile.txt</InFilePath>"
set /p string=< !TempFile!
SET PREVFILE_NM=!string:~75,-13!
set FinalreplaceLine=!string!
set TARG_FILE=%~1
REM ECHO "Before Replace FinalreplaceLine "!FinalreplaceLine!>>!DbgFile!
set FinalreplaceLine=!FinalreplaceLine:%PREVFILE_NM%=%TARG_FILE%!
ECHO "string "!string!>>!DbgFile!
ECHO "FinalreplaceLine "!FinalreplaceLine!>>!DbgFile!
::string has source string and FinalreplaceLine has target string to replace
for /f "delims=" %%a in (!INTEXTFILE!) do call :Change "%%a"
exit /b
:Change
set Text=%~1
if "%Text%"=="%string%" (
(echo !FinalreplaceLine!)>> !OUTTEXTFILE!
) else (
(echo !Text!)>> !OUTTEXTFILE!
)
exit /b

Does this work for you?:
#echo off
for /f "usebackq delims=" %%a in ("FileList.txt") do (
call :change "%%a"
type "load.xml"
pause
)
echo done
pause
goto :EOF
:change
(
echo ^<mainheader^>
echo ^<InFilePath^>D:\Data\All_Inputfiles\%~1^</InFilePath^>
echo ^</mainheader^>
) > "load.xml"

Related

Batch - Get block of text between flags, output and iterate over all files

I've got a bunch of text files in a directory that have a block of text I want to extract between two strings into a new text file of a similar name. I've got the single file working but think I've come unstuck with looping through all .txt files. Maybe at the "goto" command?
Here is the original, single file code I used:
Batch File - Find two lines then copy everything between those lines
~Top Break
foobar
~ more data title
more foobar
~Bottom Break
Garbage data
I have this code that works for a single file called FileNumber1.txt.
#echo off
set "FIRSTLINE=~Top Break"
set "LASTLINE=~Bottom Break"
set "INFILE=FileNumber1.txt"
setlocal EnableExtensions DisableDelayedExpansion
set "FLAG="
> "%INFILE%_MyData.txt" (
rem findstr configured so that each line in a file is given a "1:" number and colon.
for /F "delims=" %%L in ('findstr /N "^" "%INFILE%"') do (
set "LINE=%%L"
setlocal EnableDelayedExpansion
rem this LINE=!LINE:*:=! removes the any character before the Colon. *:
set "LINE=!LINE:*:=!"
rem this block of code checks to see if line of text = Firstline variable, if so FLAG = TRUE
if "!LINE!"=="%FIRSTLINE%" (
endlocal
set "FLAG=TRUE"
rem this block of code checks to see if line of text = Lastline variable, if so goto :Continue and end the loop
) else if "!LINE!"=="%LASTLINE%" (
endlocal
goto :CONTINUE
) else if defined FLAG (
echo(#!LINE!
endlocal
) else (
endlocal
)
)
)
:CONTINUE
endlocal
NewFile1_MyData.txt Output:
foobar
~ more data title
more foobar
I've tried to wrap this in another "FOR" loop that looks for all txt files in the same directory.
This is my code that isn't working.
#echo off
set "FIRSTLINE=~Top Break"
set "LASTLINE=~Bottom Break"
for /F %%f in (*.txt) do (
set "INFILE=%%f"
setlocal EnableExtensions DisableDelayedExpansion
set "FLAG="
> "%INFILE%_OldHeader.txt" (
rem findstr configured so that each line in a file is given a "1:" number and colon.
for /F "delims=" %%L in ('findstr /N "^" "%INFILE%"') do (
set "LINE=%%L"
setlocal EnableDelayedExpansion
rem this LINE=!LINE:*:=! removes the any character before the Colon. *:
set "LINE=!LINE:*:=!"
rem this block of code checks to see if line of text = Firstline variable, if so FLAG = TRUE
if "!LINE!"=="%FIRSTLINE%" (
endlocal
set "FLAG=TRUE"
rem this block of code checks to see if line of text = Lastline variable, if so goto :Continue and end the loop
) else if "!LINE!"=="%LASTLINE%" (
endlocal
goto :CONTINUE
) else if defined FLAG (
echo(#!LINE!
endlocal
) else (
endlocal
)
)
)
endlocal
:CONTINUE
))
The Command window gets to the "for /F" statement and exits.
Mmm... I would change the method to extract the lines for a simpler one based on lines to skip at beginning of file and number of lines to extract. After that, I would use a for to process all files and call a subroutine to extract the lines:
#echo off
setlocal EnableDelayedExpansion
set "FirstLine=~Top Break"
set "LastLine=~Bottom Break"
rem Process all text files in this folder
for %%f in (*.txt) do (
rem Search for First line and Number of lines
set "FirstNum="
for /F "delims=:" %%n in ('findstr /C:"%FirstLine%" /C:"%LastLine%" /N "%%f"') do (
if not defined FirstNum (
set "FirstNum=%%n"
) else (
set /A "LastNum=%%n-FirstNum-1"
)
)
rem Copy the lines
call :CopyLines >"%%~Nf_MyData.out" "%%f", !FirstNum!, !LastNum!
)
ren *.out *.txt
goto :EOF
:CopyLines File, Skip, Num
set "Num=%3"
for /F "usebackq skip=%2 delims=" %%a in (%1) do (
setlocal DisableDelayedExpansion
echo %%a
endlocal
set /A Num-=1
if !Num! equ 0 exit /B
)
exit /B

Get a MD5 value from a file using findstr in CMD

I have the following file contents from which I want to extract the MD5 hash value thats on line 2.
How can I do this in a Windows batch file? Unfortunately using powerscript is not an option.
Herewith the input file ( file.txt )
MD5hashoffile20160613190010_Address
f4f855c5cb40767a7227b506f641ceef
CertUtil:-hashfilecommandcompletedsuccessfully.
I wanted to use the findstr utility but the regex I use must be wrong since it's not returning anything.
findstr /R "[a-fA-F0-9]{32}" file.txt
I appreciate any advice.
Thanks
UPDATE :
I have added the full solution in the answer section.
After some trial and error I found a solution that works :
findstr /R "^[a-fA-F0-9]*$" file.txt
Updated Answer with full solution :
SETLOCAL ENABLEDELAYEDEXPANSION
SET "FILESIZE=0"
SET "RECORDCOUNT=0"
SET "MD5HASH="
SET "TEMPHASH="
SET "FILESETREPORT=_UNSET"
SET "LINE=0"
SET "COLUMNS=TableName|RecordCount|FileSize|FileHash"
echo "============================="
echo "= Starting FileSize process ="
echo "============================="
for %%F in (*.csv) do (
echo "Process A CSV File"
for /f "tokens=1,2,3,4 delims=^_" %%A IN ("%%~nF") do (
SET "TABLENAME=%%D"
SET "FILESIZE=%%~zF"
if "!FILESETREPORT!" == "_UNSET" (
SET "FILESETREPORT=%%A_%%B_%%C_FilesetReport.csv"
:: Initialize the headers
echo !COLUMNS! > !FILESETREPORT!
)
)
echo "Get RecordCount in CSV"
if "!TABLENAME!" NEQ "FilesetReport" (
for /f "tokens=*" %%I in ('more +1 %%F ^| find /v /c ""') do SET "RECORDCOUNT=%%I"
echo "Generate File MD5 Hash"
certUtil -hashfile %%~nxF MD5 > hashfile
echo "Get the hash from the file"
for /f "skip=1 tokens=*" %%A in (hashfile) do (
SET "TEMPHASH=%%A"
:: call :cleanHash
if !LINE! == 0 SET "LINE=1" && call :cleanHash
)
:: Reset the Line Number
SET "LINE=0"
echo "Save File Details to FieldsetReport"
echo "RecordCount : !RECORDCOUNT!"
echo "FileSize : !FILESIZE!"
echo "MD5Hash : !MD5HASH!"
echo "TableName : !TABLENAME!"
SET "OUTPUTLINE=!TABLENAME!|!RECORDCOUNT!|!FILESIZE!|!MD5HASH!"
echo !OUTPUTLINE! >> !FILESETREPORT!
:: Cleanup
del hashfile
)
)
echo "File Processing Completed"
exit /b 0
:cleanHash
echo "Remove all spaces from the MD5 hash"
:: for /f "delims=" %%a in ('findstr /R "^[a-fA-F0-9]*$" !TEMPHASH!') do SET TEMPHASH=%%a
SET "MD5HASH=!TEMPHASH: =!"
echo "********************************************************************"
echo !MD5HASH!
ENDLOCAL
You're better off using this:
#echo off
for /f "skip=1" %%a in (file.txt) do set "hash=%%a" &goto breakLoop
:breakLoop
echo %hash%
pause
This should work even if another line also contains only hexadecimal characters, and has the added benefit of putting the md5 hash in a variable, ready to be used.

Batch - If statement causes an error

I am parsing an xml file its format is like:
<ResourcePicture Name="a.jpg">
<GeneratedPicture Name="b.jpg"/>
<GeneratedPicture Name="c.jpg"/>
</ResourcePicture>
I can print each name of the pictures but I want to check something with an if statement inside there. However I get an error "< was unexpected at this time." but when I remove the if statement, that works just as fine. So what am I missing? Thanks in advance.
set "xmlFile=pictures.xml"
REM split xml file into lines
for /f "tokens=* skip=2" %%a in (%xmlFile%) do (
REM %%a contais a string like <ResourcePicture Name="a.jpg">
set "currnetLine=%%a"
set "currnetLine=!currnetLine:"=+!"
set counter=0
for /f "delims=+ tokens=2" %%c in ("!currnetLine!") do (
REM %%c contains the picture name like a.jpg
set /a counter=counter+1
REM CHECKING SOMETHING
if not %counter%==1 ( echo abc )
echo %%c
)
)
you need delayed expansion (I dont know if the logic of the script achieves what you want but like this it has no errors):
#echo off
set "xmlFile=pictures.xml"
REM split xml file into lines
setlocal enableDelayedExpansion
for /f "tokens=* skip=2" %%a in (%xmlFile%) do (
REM %%a contais a string like <ResourcePicture Name="a.jpg">
set "currnetLine=%%a"
set "currnetLine=!currnetLine:"=+!"
set counter=0
for /f "delims=+ tokens=2" %%c in ("!currnetLine!") do (
REM %%c contains the picture name like a.jpg
set /a counter=counter+1
REM CHECKING SOMETHING
if not !counter! == 1 ( echo abc )
echo %%c
)
)

How to assign call argument to var and echo it in Windows batch script

I want to do this:
set kommune
FOR /F "tokens=* delims=" %%x in (DBLib.txt) DO (
CALL :decryptLine "%%x"
)
GOTO:eof
:decryptLine
for /f "tokens=1,* delims==" %%a in ("%~1") do set argument=%%a & set value=%%b
set "argument=%argument:~0,-2%"
set "value=%value:~1%"
call:updateVar "%argument%" "%value%"
GOTO:EOF
:updateVar
IF "%~1" == "KommuneNavn" (
ECHO "%~2"
ECHO "KommuneNavn"
set kommune=%~2
ECHO kommune = "%kommune%" testhest
)
What it outputs:
"ABC Test Kommune"
"KommuneNavn"
"kommune = "" testhest"
How do i copy the value of the secont argument to the Variable "kommune"? And Echo it?
Edit 1: updated to exact code. "inside IF"
#ECHO OFF
SETLOCAL
set kommune
FOR /F "tokens=* delims=" %%x in (q27922463.txt) DO (
CALL :decryptLine "%%x"
)
GOTO:eof
:decryptLine
for /f "tokens=1,* delims==" %%a in ("%~1") do set "argument=%%a" & set "value=%%b"
set "argument=%argument:~0,-2%"
set "value=%value:~1%"
call:updateVar "%argument%" "%value%"
GOTO:EOF
:updateVar
IF "%~1" == "KommuneNavn" (
ECHO "%~2"
ECHO "KommuneNavn"
set kommune=%~2
CALL ECHO kommune = "%%kommune%%" testhest
)
GOTO :eof
Critical point: You haven't shown us the content of your file, so we have to construct it: and I've changed the filename to suit my system (q27922463.txt)
contents of q27922463.txt
KommuneNavnxy=yourvalue
output generated:
"ourvalue"
"KommuneNavn"
kommune = "ourvalue" testhest
Note the positioning of the quotes in the set assignments. Batch is sensitive to spaces in a SET statement. SET FLAG = N sets a variable named "FLAGSpace" to a value of "SpaceN"
So, %%a becomes KommuneNavnxy, is assigned to argument, and the last 2 characters are removed, making KommuneNavn
Similarly, %%b gets yourvalue, you remove the first and make ourvalue
Since the string kommune is set within the code block of the if statement, you need to use call echo %%var%% to display it (one of several ways).

How to find string in text file with Windows command and copy next 5 characters

I have input.txt:
asdfasfasdfa,abc12345,abc98591,abc13456,abc95934,abc53455
safasdfasdfa,abc31212,abc55455,abc23124,abc54834,abc13689
...
I need output.txt:
12345
98591
13456
95934
53455
31212
55455
23124
54834
13689
so I need find all "abc" string and copy next 5 charcters (after "abc") to new file and each number must be in new line.
Check it out:
#echo OFF &SETLOCAL
FOR %%f IN (*.txt) DO (
ECHO Processing %%f --^> %%~nf.txt.new
(for /f "usebackq delims=" %%a in ("%%~f") do call:doit "%%a")>"%%~nf.txt.new"
)
GOTO :EOF
:doit
SET "line=%~1"
SET "first=true"
:loop
SET "token="
FOR /f "tokens=1*delims=," %%b IN ("%line%") DO (
SET "token=%%b"
SET "line=%%c"
)
SET "out=%token:~-5%"
IF NOT DEFINED first ECHO(%out%
SET "first="
IF DEFINED line GOTO :loop
GOTO :EOF

Resources