Home > front end >  Batch script to Insert all lines from a text file before occurrence of a specific string
Batch script to Insert all lines from a text file before occurrence of a specific string

Time:04-09

I'm using below code for inserting text contents after a specific line/string is found. How can I modify this code to insert all the lines before the occurrence of line/string in file ?

@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)

i.e if test.txt contains:

abc
def
p q r
u v w
xyz

If the the search is for line p q r, the output should be:

abc
def

CodePudding user response:

Test if the line matches the sting, if it does, exit loop:

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

To include everything up to and including the search string, simply swop the if statement and the echo lines.

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

as a replacement to your original code:

@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

and to include the search string.

@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

Note that this will also remove any empty lines from the original file.

CodePudding user response:

@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=           
  • Related