Findstr 输出 children 和 parent

Findstr to output children and parent

我正在尝试使用命令行组织我的 xml/kml 文件。我可以使用 findstr "STRING" file.txt 找到我只需要的数据,但似乎无法从其 parent 中获取其余的 children。 kml 文件的结构类似于

<Placemark>
<name></name>
<description> [The sring data I need] </description>
<Point><coordinates></coordinates></Point>
</Placemark>

当我运行 findstr 我只得到描述数据,需要得到以上所有的东西,有什么想法吗?

grep -A3 -B2 "String" file.txt 对我有用 谢谢@zb226

还有,纯批次

set "init="
set "term="
for /F "tokens=1,* delims=[]" %%A in ('type yourFile.xml ^| find /I /N "placemark"') do (
  if not defined init (set /a init=%%A) else (set /a term=%%A)
)
for /F "tokens=1,* delims=[]" %%A in ('type yourFile.xml ^| find /N /V "^"') do (
  if %%A GEQ %init% if %%A LEQ %term% echo/%%B
)

编辑:问题是 for /F "tokens=1,* delims=[]" %%A in ('type yourFile.xml ...

行中 type 前面的引号

并写入文件

set "init="
set "term="
for /F "tokens=1,* delims=[]" %%A in ('type yourFile.xml ^| find /I /N "placemark"') do (
  if not defined init (set /a init=%%A) else (set /a term=%%A)
)
>"myFile.txt" (
  for /F "tokens=1,* delims=[]" %%A in ('type yourFile.xml ^| find /N /V "^"') do (
    if %%A GEQ %init% if %%A LEQ %term% echo/%%B
  )
)

所以任何 echo ... 被打印到 myFile.txt

如果可用,我肯定会建议您使用 grep 解决方案。 因为我很想知道如何使用批处理文件脚本来解决这个问题——毕竟这个问题被标记为 batch-file——为了完整起见,我决定 post 脚本。

请记住,在使用批处理文件执行字符串搜索时总会有一些 limitations/corner 情况。

脚本将显示由 lines 变量指定的行数。 offset 变量指定要在哪一行查找字符串。当找到多个匹配项时,仅显示最后一个匹配项。

@echo off

setlocal enabledelayedexpansion
set "source=file.txt"
set "find=[The string data I need]"
set "lines=5"
set "offset=3"

for /f "delims=:" %%e in ('findstr /n /c:"%find%" "%source%"') do (
  set /a position=%%e-offset
)

if not defined position (
  echo No matches found for: %find%
  exit /b
)

for /f "usebackq skip=%position% delims=" %%e in ("%source%") do (
  if !count!0 lss %lines%0 (
    echo %%e
    set /a count+=1
  )
)