首页 > 解决方案 > 根据文件中的某些字符串截断块

问题描述

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

;---- 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

标签: batch-file

解决方案


For根据我的评论,带有 anIf和 a 的单行单循环GoTo似乎可以执行您的问题中显示的任务:

@(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"

推荐阅读