You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改批处理脚本实现匹配指定字符串时复制两行而非一行?

Copy Matching Line + Next Line in Batch Script

Got it, let's tweak your batch script to copy both the matching line and the line immediately after it into your output file. Here's a revised version that does exactly that:

@echo off
setlocal enableextensions enabledelayedexpansion
set "sourceDir=."
set "target=output.txt"
set "searchStr=word123"

:: Clear the target file first to avoid duplicate entries on reruns
type nul > "%target%"

:: Loop through all .txt files in the source directory
for %%f in ("%sourceDir%\*.txt") do (
    :: Get line numbers of all lines containing the search string
    for /f "tokens=1 delims=:" %%n in ('findstr /i /l /n /c:"%searchStr%" "%%f"') do (
        :: Calculate the line number of the line after the match
        set /a nextLine=%%n+1
        
        :: Extract and append the matching line
        for /f "tokens=1,* delims=:" %%a in ('findstr /n "^" "%%f" ^| findstr /r "^%%n:" ^| findstr /v /r "^[0-9]*:$"') do (
            echo(%%b >> "%target%"
        )
        
        :: Extract and append the line immediately after the match (if it exists)
        for /f "tokens=1,* delims=:" %%a in ('findstr /n "^" "%%f" ^| findstr /r "^!nextLine!:" ^| findstr /v /r "^[0-9]*:$"') do (
            echo(%%b >> "%target%"
        )
    )
)
endlocal

Key Changes Explained:

  • Enabled Delayed Expansion: Added enabledelayedexpansion to handle dynamic variables like !nextLine! inside nested loops, which lets us reference the calculated next line number correctly.
  • Directory Targeting: Switched to a sourceDir variable (set to current directory by default) instead of pointing directly to a file, since your original script was scanning all .txt files. Adjust this path if your input files are in a different folder.
  • Line Number Tracking: Used findstr /n to include line numbers in search results, which lets us pinpoint both the matching line and the one right after it.
  • Next Line Calculation: For each matching line number, we compute the next line number with set /a nextLine=%%n+1, then extract both lines to append to the output.
  • Empty Line Handling: The findstr /v /r "^[0-9]*:$" filter skips entries that only have a line number (no content), so we don't write blank lines if a matched line's next line is empty.

Example Test:

If your input file contains:

aaaaayr vvvvvyr 9qeieir qei9i9r
i9iqr9r word123
s8ru9sr

The output file will have:

i9iqr9r word123
s8ru9sr

内容的提问来源于stack exchange,提问作者Arslan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:59:39