在特定字符串出现之前插入文本文件中所有行的批处理脚本

Batch script to Insert all lines from a text file before occurrence of a specific string

我使用以下代码在找到特定 line/string 后插入文本内容。如何修改此代码以插入文件中出现 line/string 之前的所有行?

@echo off
for /f "delims=:" %%i in ('findstr /rinc:"string"  test.txt') do (set line_no=%%i)
for /f "skip=%line_no% delims=" %%a in ('type test.txt') do (echo %%a >> output.txt)

即如果 test.txt 包含:

abc
def
p q r
u v w
xyz

如果搜索行 p q r,输出应该是:

abc
def

测试该行是否匹配字符串,如果匹配,退出循环:

@echo off
(for /f "delims=" %%i in ('type test.txt') do (
    if "%%i" == "p q r" exit /b
    echo %%i
 )
)>output.txt

要包含搜索字符串之前的所有内容,只需交换 if 语句和 echo 行即可。

@echo off
(for /f "delims=" %%i in ('type test.txt') do (
    echo %%i
    if "%%i" == "p q r" exit /b
 )
)>output.txt

替换您的原始代码:

@echo off
set str=
(for /f "delims=" %%i in ('type test.txt') do (
    if defined str echo %%i
    if "%%i" == "p q r" set str=1
 )
)>output.txt

并包含搜索字符串。

@echo off
set str=
(for /f "delims=" %%i in ('type test.txt') do (
    if "%%i" == "p q r" set "str=1"
    if defined str echo %%i
 )
)>output.txt

请注意,这还将删除原始文件中的所有空行。

@ECHO OFF
SETLOCAL
rem The following settings for the source directory, destination directory, filenames, 
rem and output filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "destdir=u:\your results"
SET "filename1=%sourcedir%\q71800622.txt"
SET "filename2=%sourcedir%\q71800622_2.txt"
SET "outfile=%destdir%\outfile.txt"

SET "targetline=p q r"

:: Set these flags to Y for Yes or *nothing* for No (eg. SET "showbeforetarget=")
:: show??target will show that part of the first file
:: include...??insert will show the target line before/after the insert (or both)

SET "showbeforetarget=Y"
SET "showaftertarget=Y"
SET "includetargetbeforeinsert=Y"
SET "includetargetafterinsert=Y"

SET "targetfound="


(
FOR /f "usebackqdelims=" %%b IN ("%filename1%") DO (
 ECHO %%b|FINDSTR /x /L /C:"%targetline%" >NUL
 IF ERRORLEVEL 1 (
  IF DEFINED showbeforetarget ECHO %%b
  IF DEFINED showaftertarget IF DEFINED targetfound ECHO %%b
 ) ELSE (
  SET "targetfound=Y"
  SET "showbeforetarget="
  IF DEFINED includetargetbeforeinsert ECHO %%b
  TYPE "%filename2%"
  IF DEFINED includetargetafterinsert ECHO %%b
 )
)
)>"%outfile%"

GOTO :EOF

此例程将允许在 findstr 找到匹配项的位置插入文件(我已将其设置为 /x 与显示的 /L 文字常量字符串完全匹配由 OP 提供)。

可以设置show/not显示目标字符串之前的部分,show/not显示目标字符串之后的部分,show/not显示目标字符串之前或在第二个文件的插入行(或两者)之后。