batch-file - 将周围的行返回到字符串 Windows 批处理文件

标签 batch-file windows-scripting findstr

我使用 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/

相关文章:

powershell - 将目录中一种类型的所有文件复制到一个文件夹中

java - 从 Java 执行批处理文件不能访问完整的 PATH

shell - FindStr 无法正常工作

c++ - 我如何使用 ' string::find ' 使用 C++ 在文件中查找单词

batch-file - 检查用户输入是否在txt文件中,使用批处理

windows - 我的 FTP 批处理脚本卡在 "200 PORT command successful"上,无法将文件上传到服务器

powershell - 批量隐藏Invoke-WebRequest

java - 从 Windows 批处理脚本中的 else block 执行的命令返回错误的错误级别

usb - 无需重启即可重启 USB 端口 (DevCon)

variables - 批处理脚本帮助 - 将 DelayedExpansion Var 的子字符串替换为另一个 DelayedExpansion Var