在字符串下方显示文本内容然后删除重复的行

时间:2014-07-17 21:17:14

标签: batch-file cmd

需要帮助创建批处理,该批处理从txt文件中显示一定量的文本(例如5行文本),但仅在特定关键字下方显示,例如' Home'最后删除任何重复的文本

所以,

搜索特定字符串,例如' Home' “主页”下方的任何文字都不仅仅显示5行,最后删除任何重复的句子

我尝试修改以下命令。

@echo OFF

:: Get the number of lines in the file
set LINES=0
for /f "delims==" %%I in (data.txt) do (
set /a LINES=LINES+1
)

:: Print the last 10 lines (suggestion to use more courtsey of dmityugov)
set /a LINES=LINES-10
more +%LINES% < data.txt

Displaying lines from text file in a batch file

Read every 5th line using Batch Script

我不知道是否可以删除重复项

更新

是的,右键在关键字

之后的5区块内重复

然而,不要担心删除重复项,我主要关心的是尝试在某个字符串下面显示文字,例如Home

我有下面的命令,但没有显示文本下面的所有信息,只有一行理想情况下我想调整显示的数量,例如5行数据

setlocal EnableDelayedExpansion
rem Assemble the list of line numbers
set numbers=
set "folder=C:\test\world.txt"
for /F "delims=:" %%a in ('findstr /I /N /C:"home" "%folder%"') do (
set /A before=%%a-0, after=%%a+3
set "numbers=!numbers!!before!: !after!: "
)
rem Search for the lines
(for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "%folder%" ^| findstr /B  "%numbers%"') do echo. %%b)

batch script to print previous and next lines of search string in a text file

1 个答案:

答案 0 :(得分:1)

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
:: remove variables starting $
For %%b IN ($) DO FOR  /F "delims==" %%a In ('set %%b 2^>Nul') DO SET "%%a="
SET /a before=0
SET /a after=5
SET "target=home"
SET /a count=0
SET "file=q24813694.txt"
FOR /f "delims=:" %%a IN ('findstr /i /n /L /c:"%target%" "%file%"'
 ) DO SET /a $!count!=%%a-%before%&SET /a count+=1
FOR /f "tokens=1*delims=:" %%a IN ('findstr /n /r "." "%file%"') DO (
 SET "printed="
 FOR /f "tokens=1,2delims==" %%m IN ('set $ 2^>nul') DO IF NOT DEFINED printed IF %%a geq %%n (
  SET /a count=%%n+%before%+%after%
  IF %%a geq !count! (SET "%%m=") ELSE (SET "printed=Y"&ECHO %%b)
 )
)

GOTO :EOF

这个例程应该可以解决问题。当然,您需要设置file以适合自己;并设置target

如果要设置打印前的行数以及之后的行数(包括目标行),那么这些也应该有效。