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
解决方案
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"
推荐阅读
- perl - 如何在 File::Find::Rule 的 `or` 替代项中使用 mindepth 和 maxdepth?
- docker - 暂停时的 docker 容器在快照时是否具有与 VM 类似的特性?
- c# - 从 .NET 和 Python 连接 o google 电子表格
- imacros - 如何在 iMacros 中使用数组循环?
- javascript - 为什么隐式 args 调用在显式时不起作用?
- php - docker debian 拉伸图像中缺少 php-redis 存储库
- php - Heroku 降级 PHP 版本
- java - 随机数游戏问题(用户选号,电脑猜)
- vb6 - VB6 ADODC 控件属性连接字符串,在其他PC上不起作用需要用户路径名
- acumatica - 采购收据下达执行超时