Findstr second column and make new batch - batch-file

As you can see, the batch file makes a VBS script and it should make another batch file, but it doesn't, since findstr /R "^ECHO" "%~sf0" >> "temp.bat"
copies the code including the echo. I want to copy the line after ECHO and place them in a temporary file.
Here is my code
#echo off
echo This is batch
:::wscript.echo "This VBScript"
:::wscript.echo "Today is " & day(date) & "-" & month(date) & "-" & year(date)
findstr "^:::" "%~sf0">temp.vbs & cscript //nologo temp.vbs & del temp.vbs
goto b
ECHO #echo off
ECHO setlocal enabledelayedexpansion
ECHO set SCRIPT_INSTANCES=20
ECHO :: Create a temporary file if one doesn't already exist
ECHO if not exist script_count.txt >script_count.txt echo(%SCRIPT_INSTANCES%
ECHO :: Read in the value of the config file
ECHO set /p script_counter=<script_count.txt
ECHO :: If the value of script_counter is greater than 1, decrement it and start again
ECHO if %script_counter% gtr 1 (
ECHO set /a script_counter-=1
ECHO >script_count.txt echo(!script_counter!
ECHO
ECHO start "" cmd /c "%~0"
ECHO ) else (
ECHO del script_count.txt
ECHO )
ECHO color a
ECHO :a
ECHO tree C:/
ECHO goto a)
:b
findstr /R "^ECHO" "%~sf0" >> "temp.bat"
pause
exit

You can strip off the leading echo by using the space as a delimiter.
So change this line.
findstr /R "^ECHO" "%~sf0" >> "temp.bat"
To this
FOR /F "TOKENS=1* DELIMS= " %%G IN ('findstr /R "^ECHO" "%~sf0"') DO echo %%H >>"temp.bat"
One drawback to this code is that it will strip all the indentation of your code.

Related

How do i make the vbs file to work properly?

When i tried to create a vbs file with batch, this line doesn't show in the vbs file
echo WScript.Sleep 2000 : Objshell.Run "taskkill /f /im cmd.exe", 0 >> 2.vbs
What do i need to escape or something to make the vbs file runnable ?
Thanks!
I made a new batch code to make life easier for users in order to integrate some vbs files that will be generated automatically with a batch file when we execute it.
This batch code is based on search and replace using Regex with vbscript.
So, the user can just drag and drop a vbscript over this batch script. And voila !
#echo off
Title Vbs2Bat Intergration using Regex with vbscript by Hackoo 2020
Set "InputFile=%~1"
If ["%InputFile%"] EQU [""] Goto :Help
Set "TempFile=%Temp%\%~n1.tmp"
Set "OutPutFile=%~dpn1_.txt"
Call :Search_Replace "%InputFile%" "%TempFile%"
REM ------------------------Generate the formatted file------------------------------
> "%OutPutFile%" (
echo #echo off
echo Call :Generate_VBS_File
echo Call :Execute_VBS_File
echo REM -----------------------------------------------------------------------------
echo :Generate_VBS_File
echo ^>"%%tmp%%\%%~n0.vbs" (
)
>> "%OutPutFile%" (#for /f "tokens=* delims=" %%a in ('Type "%TempFile%"') do echo. echo %%a)
>> "%OutPutFile%" (
echo ^)
echo Exit /B
echo REM -----------------------------------------------------------------------------
echo :Execute_VBS_File
echo cscript //nologo "%%tmp%%\%%~n0.vbs"
echo If Exist "%%tmp%%\%%~n0.vbs" Del "%%tmp%%\%%~n0.vbs"
echo Exit /B
echo REM -----------------------------------------------------------------------------
)
REM ---------------------------------------------------------------------------------
If Exist "%TempFile%" Del "%TempFile%"
If Exist "%OutPutFile%" Start "" "%OutPutFile%" & Exit
::-----------------------------------------------------------------------------------
:Search_Replace <InputFile> <OutPutFile>
(
echo WScript.StdOut.WriteLine Search_Replace(Data^)
echo Function Search_Replace(Data^)
echo Dim strPattern, strReplace, strResult,oRegExp
echo Data = "%~1"
echo Data = WScript.StdIn.ReadAll
echo Set oRegExp = New RegExp
echo oRegExp.Global = True
echo oRegExp.Multiline = True
echo oRegExp.IgnoreCase = True
echo strPattern1 = "[)&<|>]"
echo oRegExp.Pattern = strPattern1
echo strReplace1 = "^$+"
echo strResult1 = oRegExp.Replace(Data,strReplace1^)
echo strPattern2 = "[%%]"
echo oRegExp.Pattern = strPattern2
echo strReplace2 = "%%$+"
echo strResult2 = oRegExp.Replace(strResult1,strReplace2^)
echo Search_Replace = strResult2
echo End Function
)>"%tmp%\%~n0.vbs"
cscript //nologo "%tmp%\%~n0.vbs" < "%~1" > "%~2"
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
Exit /B
::----------------------------------------------------------------------------------
:Help
Mode 70,4 & Color 0C
echo(
echo You should drag and drop a VBS file over,
echo this script "%~nx0" to be converted !
Timeout /T 10 /NoBreak>nul
Exit
::----------------------------------------------------------------------------------

Batch: Filter filename

I have lot file that need to filter before move to other folder.
The filter condition:
[PEQ]*_[+-][1-9][0-9]_[P-R][0-9]_*[._][0-9]*
Example of filename:
P101_+19_R0_3.0_QA.txt
I try to apply the filter in batch script but nothing happen.
Am i correctly defined the filter?
My script:
SET _ext1=txt
SETLOCAL ENABLEDELAYEDEXPANSION
for %%f in (%_source%\[PEQ]*_[+-][1-9][0-9]_[P-R][0-9]_*[._][0-9]*.%_ext1%) do (
echo %%f >> %LOG%
SET _path=%%~df%%~pf
echo !_path! >> %LOG%
SET _filename=%%~nf
echo !_filename! >> %LOG%
echo. >> %LOG%
echo Processing !_filename! >> %LOG%
IF EXIST !_path!!_filename!*.%_ext1% (
copy /Y "!_path!!_filename!*.%_ext1%" "%_target%" >> %LOG%
)
)
ENDLOCAL
I hope you understand the difference between a wildcard * matching any number of any chars and the RegEx * which means any number (also zero) of the previous match. Together with the RE . any char .* will resemble the wildcard *
#Echo off & SETLOCAL ENABLEDELAYEDEXPANSION
SET _ext1=txt
for /f "delims=" %%f in (
'dir /B "%_source%\*_*_*_*.%_ext1%" ^| Findstr /i "%_source%\[PEQ]*_[+-][1-9][0-9]_[P-R][0-9]_.*[._][0-9]*.%_ext1%" '
) do (
echo %%f >> %LOG%
SET _path=%%~df%%~pf
echo !_path! >> %LOG%
SET _filename=%%~nf
echo !_filename! >> %LOG%
echo. >> %LOG%
echo Processing !_filename! >> %LOG%
IF EXIST !_path!!_filename!*.%_ext1% (
copy /Y "!_path!!_filename!*.%_ext1%" "%_target%" >> %LOG%
)
)
ENDLOCAL
You should first test the line with the dir and findstr in an open cmd window,
then without the escaping ^ and surrounding '
dir /B "%_source%\*_*_*_*.%_ext1%"
If this fits as a first selection add
dir /B "%_source%\*_*_*_*.%_ext1%" | Findstr /i "%_source%\[PEQ]*_[+-][1-9][0-9]_[P-R][0-9]_.*[._][0-9]*.%_ext1%"
And vary your RegEx until it does what you want.
Remember that findstr RegEx capabilities are quite limited.

Batch file finding a filename which contains a substring

I want to write a batch file to find all .vsdm files and the file name must contain a substring "2.4". But my code is telling me that all my .vsdm files contains the substring "2.4" which is not correct.
FOR /R %completepath% %%G IN (*.vsdm) DO (
set file=%%~nG
If not "%file%"=="%file:2.4=%" (
echo Filename contains 2.4
) else (
echo Filename does NOT contains 2.4
)
)
Can anyone tell me where did I get it wrong?Thanks
If "%file%"=="%file:2.4=%" (
echo Filename "%file%" does NOT contain 2.4
) else (
echo Filename "%file%" contains 2.4
)
Including the filename in the echo may reveal more. I can see no reason for the double-negative approach. The way the code operates may depend on precisely where in code the instructions are located, for instance if these lines are contained within any variety of loop or code-block, operation may depend on other elements, so it's important to present the code in-context and with an example of what was expected and what actually happened.
correct fomatting makes all clear.
There are one or two SO articles about delayed expansion which OP should become familiar with.
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /R %completepath% %%G IN (*.vsdm) DO (
set "file=%%~nG"
If not "!file!"=="!file:2.4=!" (
echo Filename contains 2.4
) else (
echo Filename does NOT contains 2.4
)
)
ENDLOCAL
You can use the command Where /? that let you use wildcard characters ( ? * ) and UNC paths.
#echo off
Title Find the location of a file with substring by Hackoo
Color 0A
Call :inputbox "Enter the file name to search :" "Enter the file name to search"
If "%input%" == "" Color 0C & (
echo(
echo You must enter a filename to continue with this program
pause>nul & exit
) else (
Call :Browse4Folder "Select the source folder to scan %input%" "c:\scripts"
)
Set "ROOT=%Location%"
::We check whether the input string has an anti-Slach in the end or no ? if yes, we remove it !
IF %ROOT:~-1%==\ SET ROOT=%ROOT:~0,-1%
set whereCmd=where.exe /r %ROOT% %input%
for /f %%a in ('%whereCmd%') do echo %%~nxa --^> %%a
pause & exit
::***************************************************************************
:Browse4Folder
set Location=
set vbs="%temp%\_.vbs"
set cmd="%temp%\_.cmd"
for %%f in (%vbs% %cmd%) do if exist %%f del %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
(
echo set shell=WScript.CreateObject("Shell.Application"^)
echo set f=shell.BrowseForFolder(0,"%~1",0,"%~2"^)
echo if typename(f^)="Nothing" Then
echo wscript.echo "set Location=Dialog Cancelled"
echo WScript.Quit(1^)
echo end if
echo set fs=f.Items(^):set fi=fs.Item(^)
echo p=fi.Path:wscript.echo "set Location=" ^& p
)>%vbs%
cscript //nologo %vbs% > %cmd%
for /f "delims=" %%a in (%cmd%) do %%a
for %%f in (%vbs% %cmd%) do if exist %%f del /f /q %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
goto :eof
::***************************************************************************
:InputBox
set "input="
set "heading=%~2"
set "message=%~1"
echo wscript.echo inputbox(WScript.Arguments(0),WScript.Arguments(1)) >"%temp%\input.vbs"
for /f "tokens=* delims=" %%a in ('cscript //nologo "%temp%\input.vbs" "%message%" "%heading%"') do (
set "input=%%a"
)
exit /b
::***************************************************************************

Pinging Multiple PCs and Adding Text

I'm pretty new to this so please bear with me, and if you require anymore information from me please say. Thanks in advance for your help.
I have this code that pings different PCs then returns back if they are online/offline. I wanted to know if you could add another column once the bat file has ran its ping test so it has the computer name next to it.
#echo off
if exist C:\tools\computers.txt goto Label1
echo.
echo Cannot find C:\tools\computers.txt
echo.
Pause
goto :eof
:Label1
echo PingTest executed on %date% at %time% > C:\tools\z.txt
echo ================================================= >> C:\tools\z.txt
for /f %%i in (C:\tools\computers.txt) do call :Sub %%i notepad C:\tools\z.txt
goto :eof
:Sub
echo Testing %1 set state=alive ping -n 1 %1 | find /i "bytes=" || set state=dead echo %1 is %state% >> C:\tools\z.txt
The bat file creates a document that shows the following;
PingTest executed on 28/07/2016 at 13:10:28
99.1.82.28 is alive
99.1.82.100 is alive
ect.
If possible I would like the bat file to run so it displays this;
The bat file creates a document that shows the following;
PingTest executed on 28/07/2016 at 13:10:28
Computer 1 : 99.1.82.28 is alive
Computer 2 : 99.1.82.100 is alive
ect.
--
Would appreciate any help & guidance on this.
Thanks.
You can try this solution :
#echo off
Title Ping Test
set "URLS=URLS.txt"
set "LogFile=PingResults.txt"
If exist %LogFile% Del %LogFile%
(
echo ******************************************************
echo PingTest executed on %Date% # Time %Time%
echo ******************************************************
echo(
) > %LogFile%
Setlocal EnableDelayedExpansion
for /f "usebackq delims=" %%a in ("%URLS%") do (
for /f "tokens=2 delims=[]" %%b in ('ping -n 1 %%a') do set "ip=%%b"
ping -n 1 %%a>nul && set "msg=%%a : !ip! ALive ok" || set "msg=%%a : !ip! Dead failed to respond"
echo !msg!
echo !msg! >> %LogFile%
)
)
EndLocal
Start "" %LogFile%
pause>nul & exit
EDIT : on 29/07/2016 # 12:48
Another version with multi-colors : Special thanks goes to ICARUS for the color function (-_°)
#echo off
Rem Special thanks goes to Iracus for the color function (-_°)
mode con cols=60 lines=20
Title Multi-Ping hosts Tester with Multi-colors by Hackoo
set "URLS=URLS.txt"
set "LogFile=PingResults.txt"
If exist %LogFile% Del %LogFile%
call :init
echo(
call :color 0E "------- Ping Status of Computers hosts -------" 1
echo(
(
echo ******************************************************
echo PingTest executed on %Date% # Time %Time%
echo ******************************************************
echo(
) > %LogFile%
Setlocal EnableDelayedExpansion
for /f "usebackq delims=" %%a in ("%URLS%") do (
for /f "tokens=2 delims=[]" %%b in ('ping -n 1 %%a') do set "ip=%%b"
ping -n 1 %%a>nul && set "msg=%%a - !ip! ALive ok" && Call :Color 0A "!msg!" 1 || set "msg=%%a - !ip! Dead failed to respond" && Call :Color 0C "!msg!" 1
echo !msg! >> %LogFile%
)
)
EndLocal
Start "" %LogFile%
pause>nul & exit
:init
prompt $g
for /F "delims=." %%a in ('"prompt $H. & for %%b in (1) do rem"') do set "BS=%%a"
exit /b
:color
set nL=%3
if not defined nL echo requires third argument & pause > nul & goto :eof
if %3 == 0 (
<nul set /p ".=%bs%">%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
) else if %3 == 1 (
echo %bs%>%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
)
exit /b
EDIT : Update On 23/08/2016
http://pastebin.com/zjYwSqUM

How to do while loop in windows batch

I wrote a windows batch script to check and move files to another directory based on the list I put in a notepad file named list.txt. But I have no idea that how to set the while-loop. Only to jump out of the subroute when the condition fulfill.
In C Programming, we could write like this by setting a while-loop direcly. But seems in windows batch is quite different.
All I want is like this:
Directory A:
1. A.txt
2. B.txt
3. list.txt (By line sequential with filename want to move)
4. process.bat
Directory B:
None of files (Then move a file by order of line set in list.txt) OR
A.txt (If already existed a text file in directory, process.bat will pause before A.txt disappear)
Process.bat
#echo off
:readline
for /f "tokens=*" %%a in (list.txt) do call :processline %%a
goto :eof
:processline
if exist D:\DirectoryA\*.txt (
echo %time% >> D:\AutoLog\Log.txt
echo Previous job did not finished yet. >> D:\AutoLog\Log.txt
Timeout /t 30
echo.
)
set name=%*
if exist %name%.txt (
echo %time% >> D:\AutoLog\Log.txt
echo File found and processing %name%.txt now... >> D:\AutoLog\Log.txt
copy "%~dp0\%name%.txt" "D:\DirectoryB"
echo Transfer %name%.txt completed!! >> D:\AutoLog\Log.txt
echo. >> D:\AutoLog\Log.txt
Timeout /t 790
echo.
echo ==============================================================
)
:eof
Please guide me to finish the script by using a while-loop method. Thanks
I change some script sequence and it works now.
#echo off
:readline
for /f "tokens=*" %%a in (list.txt) do call :processline %%a
goto :eof
:processline
set name=%*
if exist C:\Test2\*.txt (
echo %date% %time% >> C:\Test2\Log.txt
echo Previous job did not finished yet. >> C:\Test2\Log.txt
Timeout /t 5
echo.
echo. >> C:\Test2\Log.txt
goto :processline
)
if exist %name%.txt (
echo %date% %time% >> C:\Test2\Log.txt
echo File found and processing %name%.txt now... >> C:\Test2\Log.txt
copy "%~dp0\%name%.txt" "C:\Test2"
echo Transfer %name%.txt completed!! >> C:\Test2\Log.txt
echo. >> C:\Test2\Log.txt
Timeout /t 10
echo.
echo ==============================================================
)
:eof
This will copy as well as count the number of lines from your text file..
# echo off
:TextPath
cls
set /p Input=#1 Enter the full path of the text file :
set /p Source=#2 Enter the full path of Source :
set /p Target=#3 Enter the full path of Destination :
:choice
set /P c=Ready to Continue[Y/N]?
if /I "%c%" EQU "Y" goto :Yes
if /I "%c%" EQU "N" goto :No
goto :choice
:Yes_Local
for /f "delims=" %%i in (%Input%) do echo f| xcopy /f /y "%Source%\%%i" "%Target%\%%i"
for /f %%C in ('Find /V /C "" ^< %Input%') do set Count=%%C
msg * No of Lines executed= %Count%
exit
:No
cls
color e
echo Redirecting to Main....
PING 127.0.0.1 -n 2 >NUL
cls
echo Please wait
PING 127.0.0.1 -n 4 >NUL
goto TextPath

Resources