使用批处理删除文本文件中特定单词之前的文本
Posted
技术标签:
【中文标题】使用批处理删除文本文件中特定单词之前的文本【英文标题】:Delete text before specific word in text file using batch 【发布时间】:2021-05-16 18:34:03 【问题描述】:这是我正在寻找的示例。假设我们有一个包含以下内容的文本文件:
eggs bacon
delete me here
test me
delete this too here
我想要一个批处理文件,删除“这里”一词之前的所有内容,但只删除同一行中的所有内容。
所以输出应该是:
eggs bacon
here
test me
here
我尝试使用 for 循环逐个标记解析文本标记,但它让我无处可去。
【问题讨论】:
【参考方案1】:@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
【讨论】:
以上是关于使用批处理删除文本文件中特定单词之前的文本的主要内容,如果未能解决你的问题,请参考以下文章