我正在尝试使用命令行组织我的xml / kml文件。我可以使用findstr "STRING" file.txt
来查找我只需要的数据,但似乎无法从其父级中获取其余的子项。 kml文件的结构类似于
<Placemark>
<name></name>
<description> [The sring data I need] </description>
<Point><coordinates></coordinates></Point>
</Placemark>
当我运行findstr
时,我只获取描述数据并需要获得以上所有内容,任何想法?
答案 0 :(得分:1)
grep -A3 -B2“String”file.txt为我工作 谢谢@ zb226
答案 1 :(得分:1)
另外,纯批次
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
)
编辑:问题是行type
for /F "tokens=1,* delims=[]" %%A in ('type yourFile.xml ...
前面的引文
并写入文件
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
答案 2 :(得分:1)
我肯定会建议您在可用时使用grep
解决方案。
因为我有兴趣看看如何通过批处理文件脚本来解决问题 - 毕竟问题是用batch-file
标记的 - 为了完整起见,我还是决定发布脚本。
请记住,在使用批处理文件执行字符串搜索时总会存在一些限制/极端情况。
脚本将显示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
)
)