简体   繁体   中英

Delete text before specific word in text file using batch

Here's an example of what I'm looking for. Let's say we have a text file that contains the following:

eggs bacon
delete me here
test me 
delete this too here

I want to have a batch file that deletes everything before the word "here" but only everything on the same line.

So the output should be:

eggs bacon
here
test me
here

I've tried using for loops to parse the text token by token but it's getting me nowhere.

@ECHO Off
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following settings for the source directory, destination directory, target directory,
rem batch directory, filenames, output filename and temporary filename [if shown] 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%\q66181497.txt"
SET "outfile=%destdir%\outfile.txt"

SET "dropbefore=here"

(
FOR /f "usebackqdelims=" %%b IN ("%filename1%") DO (
 rem transfer line read to variable "line" for manipulation
 SET "line=%%b"
 IF "%%b" equ "!line:*%dropbefore%=!" (
  rem target text missing from line
  ECHO %%b
 ) ELSE (
  rem target found on line. replace all-before-target with target
 ECHO !line:*%dropbefore%=%dropbefore%!
 )
)
)>"%outfile%"
GOTO :EOF

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM