根据文件中的某些字符串截断块

时间:2018-11-26 19:36:49

标签: batch-file

我有一个任务是从文件中间的某些字符串开始切下块,然后将文件的上部保存到新文件中。

;---- Some text A
aaaaaaa1111
……..
aaaaaaa2222
;-----Some text B
bbbbbbbbb1111
………….. 
bbbbbbbbb2222

现在我正在寻找一个批处理文件以切断从以下位置开始的零件:

;-----Some text B

因此,剪切后,新文件如下所示:

;---- Some text A
aaaaaaa1111
……..
aaaaaaa2222

所有部分均始于:

;-----Some text B
bbbbbbbbb1111
………….. 
bbbbbbbbb2222

已被切断。

我尝试使用DOStip中的功能,然后按如下所示调用该功能:

@ECHO OFF
REM.-- Prepare the Command Processor
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION
echo.Extracting hello world block into "Load_SDK.M83" file
call:extractFromFile ";---- Some text A" ";---- Some text B">"Load_SDK.M83"
:extractFromFile - extract lines from a file between begin and end mark
:: - %~1: begin mark, use '...$' mark to allow variable substitution
:: - %~2: optional end mark, default is end of file
:: - %~3: optional source file, default is THIS file
SETLOCAL
set bmk=;---- Some text A
set emk=;---- Some text B
set src=C:\Files\Load_all.M83
set /a b=-1
set /a e=-1
if "%src%"=="" set src=%~f0& ::- if no source file then assume THIS file
for /f "tokens=1,* delims=:" %%a in ('"findstr /n /b /c:"%bmk%" "%~f0""') do (
    set b=%%a
    set bmk=%%b
)
if /i %b%==-1 echo.ERROR: begin mark '%bmk%' not found in '%src%'&GOTO:EOF
if "%emk%"=="" (set /a e=2000000000) ELSE (
    for /f "delims=:" %%a in ('"findstr /n /b /c:"%emk%" "%~f0""') do (
        if /i %b% LSS %%a if /i !e!==-1 set e=%%a& rem -- find only the first one after b
    )
)
if /i %e%==-1 echo.ERROR: end mark '%emk%' missing in '%src%'&GOTO:EOF
if /i %b% GEQ %e% echo.ERROR: end mark '%emk%' detected before begin mark '%bmk%' in '%src%'&GOTO:EOF
for /f "delims=: tokens=1,*" %%a in ('"findstr /v /n /b /c:"#$*ReturnAll*$#" "%src%""') do (
    if /i %b% LSS %%a if /i %%a LSS %e% (
        if "%bmk:~-1%"=="$" (
            rem --sustitution variables within %%b
            call echo.%%b
        ) ELSE (
            rem --no variable substitution
            echo.%%b
        )
    )
)
GOTO:EOF

1 个答案:

答案 0 :(得分:0)

根据我的评论,单行ForIfGoTo的循环似乎执行了您的问题所示的任务:

@(For /F UseBackQDelims^=^ EOL^= %%A In ("source.txt") Do @If /I Not "%%A"==";-----Some text B" (Set /P "=%%A"<Nul&Echo=) Else GoTo :EOF)>"result.txt"