[英]How to delete one line before a specific word in a text file in python
[英]Delete text before specific word in text file using batch
這是我正在尋找的一個例子。 假設我們有一個包含以下內容的文本文件:
eggs bacon
delete me here
test me
delete this too here
我想要一個批處理文件,刪除“這里”一詞之前的所有內容,但只刪除同一行中的所有內容。
所以 output 應該是:
eggs bacon
here
test me
here
我嘗試使用 for 循環逐個解析文本標記,但它讓我無處可去。
@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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.