为了简洁起见,我有一个文本文件(在Windows中),看起来像这样:
Blah Blah Blah Blah Blah Blah Blah 2016 START-OF-FILE ABC ABCDE Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah END-OF-FILE Blah Blah Blah Blah Blah Blah
我只想要文件开始和结束文件之间的文本
ABC ABCDE Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah
我尝试使用Findstr,但不太工作。 有人可以帮忙吗?
这是我到目前为止:
@echo off setlocal enabledelayedexpansion set quote= for /f "tokens=*" %%a in (infile.txt) do ( set str=%%a set str=!str:"=:! if not "!str!"=="!str::=!" ( if defined quote ( set quote= for %%b in (^"%%a) do set str=%%~b if not "!str!"==START-OF-FILE if not "!str: =!"==END-OF-FILE echo !str! >> outfile.txt ) else ( set quote=1 for %%b in (%%a^") do set str=%%~b ) ) if defined quote ( if not "!str!"==START-OF-FILE if not "!str: =!"==END-OF-FILE echo !str! >> outfile.txt ) )
这是结果:
2016" START-OF-FILE ABC ABCDE Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah END-OF-FILE Blah Blah Blah
我需要2016年“,文件开始,文件结束和行结束后(Blah Blah Blah)不包括在内
@echo off setlocal EnableDelayedExpansion set "skip=" for /F "delims=:" %%a in ('findstr /N "START-OF-FILE END-OF-FILE" input.txt') do ( if not defined skip ( set "skip=%%a" ) else ( set /A "lines=%%a-skip-1" ) ) (for /F "skip=%skip% delims=" %%a in (input.txt) do ( echo %%a set /A lines-=1 if !lines! equ 0 goto break )) > output.txt :break
@ECHO OFF SETLOCAL SET "sourcedir=U:\sourcedir" SET "destdir=U:\destdir" SET "filename1=%sourcedir%\q36416492.txt" SET "outfile=%destdir%\outfile.txt" SET "output=" ( FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO ( IF "%%a"=="END-OF-FILE" SET "output=" IF DEFINED output ECHO(%%a IF "%%a"=="START-OF-FILE" SET "output=Y" ) )>"%outfile%" GOTO :EOF
您将需要更改sourcedir
和destdir
的设置以适合您的情况。
我使用了一个名为q36416492.txt
的文件, q36416492.txt
包含我的测试数据。
生成定义为%outfile%的文件
使用if defined
的事实if defined
解释变量的运行时间值。
读取文件的每一行,如果ON触发字符串匹配,则将output
设置为一个值,并清除OFF触发字符串匹配的值。 如果标志output
已定义,则只能反弹。
您可以使用
String[] lines = Files.readAllLines(Paths.get("myfile.txt"));
以文件的所有行作为数组。 从那里循环,找到你想要的东西很简单。
String result = ""; boolean withinBounds = false; for (int i = 0; i < lines.length; i++) { if (lines[i].equals("START-OF-FILE")) { withinBounds = true; } if (lines[i].equals("END-OF-FILE")) { withinBounds = false; } if (withinBounds) { //do whatever you want to do with the lines between your tags here result = result + lines[i] + "\n"; } }
请注意,这是未经测试的,但一般的概念肯定适合你。 注意它也假设你的标签将自己在一行。
使用Windows Powershell
如果你知道你的开始和结束点,这将是一个两步过程。 第一行切断顶部,第二行切断底部。
get-content file.txt | select -last n > output.txt
get-content output.txt | 选择-first n > output2.txt
如果你不知道你的起点和终点在哪里,它将需要这个额外的步骤两次。
键入 file.txt | select-string -pattern “START_OF_FILE” | 选择对象LineNumber
键入 file.txt | select-string -pattern “END_OF_FILE” | 选择对象LineNumber