Andreas_Lng
Andreas_Lng

Reputation: 1197

Windows batch skip lines until specific string occures

I have multiple text-files that begins with some lines followed by a line (the n-th line) which contains a specific string. This string is unique in each file. What i would like to do is to remove the first n lines and keep the other lines in the file. I tried this using:

@echo off

FOR %%G IN ("%~dp0\*.txt") DO (
    FOR /f "skip=3 delims=*" %%a IN (%%G) DO (
        ECHO %%a >>%~dp0\out\%%~nG.txt
    ) >nul
)

But this will just skip a fixed number of lines. I've then tried to get the line number of the key-word-line with

FIND /N "KEY_WORD" %%G

At this point i don't know how to extract the line number from the result of the FIND command. Is there any other solution?

Thanks in advance.

Edit: Example file

line_1
line_2
line_3
key_word
line_4
line_5
...

I just want to keep anything behind "key_word". The output of this example should be:

line_4
line_5
...

Upvotes: 0

Views: 2677

Answers (3)

gbabu
gbabu

Reputation: 1108

Here is a way with an example.

Code -

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

Sample-

D:\Scripts\dummy>type input.txt
line_1
line_2
line_3
key_word
line_4
line_5
line_6


D:\Scripts\dummy>type draft.bat
@echo off
for /f "delims=:" %%i in ('findstr /rinc:"key_word"  input.txt') do (set line_no=%%i)
for /f "skip=%line_no% delims=" %%a in ('type input.txt') do (echo %%a)


D:\Scripts\dummy>draft.bat
line_4
line_5
line_6

Cheers,G

Upvotes: 1

Magoo
Magoo

Reputation: 80211

Perhaps

for /f %%a in ('find /n "KEY_WORD" %%G') do (
 set linenum=%%a
 echo line %%a selected
)
...
echo linenum=%linenum%

but without a clue as to exactly what you want by way of an example, difficult to scry.

Upvotes: 0

foxidrive
foxidrive

Reputation: 41307

Here's a robust method to remove the start of a file until it finds "some string" on a line, inclusive.

The terms are regular expressions.

type "file.txt" |findrepl /v "." /e:"some string" >"newfile.txt"

This uses a helper batch file called findrepl.bat (by aacini) - download from: https://www.dropbox.com/s/rfdldmcb6vwi9xc/findrepl.bat

Place findrepl.bat in the same folder as the batch file or on the path.

Upvotes: 0

Related Questions