我使用 findstr
按以下方式在文件中搜索字符串:
findstr "test" file.txt
这将返回找到 test
的行,但我想返回匹配行上方和下方的 3 行。我看了一下,似乎没有任何内置选项可以让 findstr
返回周围的行。
最佳答案
给你
@echo off
setlocal enabledelayedexpansion
for /f "tokens=1 delims=:" %%a in ('findstr /n "hello" file.txt') do (
set /a line=%%a
)
set /a num=0
for /l %%b in (3,-1,1) do (
set /a lines[!num!]=!line!-%%b
set /a num+=1
)
for /l %%c in (1,1,3) do (
set /a lines[!num!]=!line!+%%c
set /a num+=1
)
set /a count=1
for /f "tokens=* delims=" %%d in (file.txt) do (
for /l %%e in (%lines[0]%,1,%lines[5]%) do (
if !count!==%%e if not %%e==!line! echo %%d
)
set /a count+=1
)
pause >nul
关于batch-file - 将周围的行返回到字符串 Windows 批处理文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14646162/