问题
I use the below batch script which has binary part (.exe program) append to the bottom of the script. I used this trick to attach binary part to my batch script:
::Append binary part to your batch file with COPY
copy /y /a "batchscript.bat" + /b program.exe /b combined.bat
In order to extract the binary part from the batch script (combined.bat), I use the following method with "findstr" command:
;;;===,,, @ECHO OFF
;;;===,,, SETLOCAL ENABLEEXTENSIONS
;;;===,,,
;;;===,,, echo test line1
;;;===,,, echo test line2
;;;===,,,
;;;===,,, findstr /v "^;;;===,,," %~f0 > program.exe
;;;===,,,
;;;===,,, echo test line3
;;;===,,, echo test line4
;;;===,,, exit /b
;;;===,,, ::Below are binary data for program.exe
binarybinarybinarybinarybinarybinarybinarybinarybinarybinarybinarybinary
binarybinarybinarybinarybinarybinarybinarybinarybinarybinarybinarybinary
...
So this piece of code extracts the binary part from the script to program.exe:
findstr /v "^;;;===,,," %~f0 > program.exe
But as a down-side, each line of the script part must begin with following prefix
;;;===,,,
What I want to do is to use the prefix ";;;===,,," only at the last line of code and extract all binary data after this line. Is it possible to achieve this via some crazy combination of findstr + for loop + if command? Example:
@ECHO OFF
SETLOCAL ENABLEEXTENSIONS
echo test line1
echo test line2
HERE IS THE CODE TO EXTRACT BINARY PART AFTER LAST SCRIPT LINE
echo test line3
echo test line4
exit /b
;;;===,,, ::Below are binary data for program.exe
binarybinarybinarybinarybinarybinarybinarybinarybinarybinarybinarybinary
binarybinarybinarybinarybinarybinarybinarybinarybinarybinarybinarybinary
...
Many thanks in advance.
回答1:
@echo off
setlocal
rem Get the line number of the dividing line
for /F "delims=:" %%a in ('findstr /N "^;;;===,,," "%~F0"') do set "lines=%%a"
rem Extract the binary part from this file
< "%~F0" (
rem Pass thru the first lines
for /L %%i in (1,1,%lines%) do set /P "="
rem Copy the rest
findstr "^"
) > program.exe
goto :EOF
;;;===,,, ::Below are binary data for program.exe
This program is functionally equivalent to your code, that is, this program will fail when your program fails. You should know that findstr
command can not successfully copy binary data in all cases.
This solution makes good use of the fact that findstr
command does not move the file pointer of the redirected input file that is leaved at the right place from the previous set /P
commands.
来源:https://stackoverflow.com/questions/33541938/how-to-extract-binary-data-from-batch-file-using-findstr-command