使用CMD提取文本文件第四行中的第六个单词

时间:2018-10-07 12:14:57

标签: windows batch-file cmd

我试图从第4行中提取第6个单词,但是循环无法正常工作,谁能说出所使用命令的语法错误

@echo off
for %%a in ("D:\H Drive\subh\test\OUTPUT\*.*") do (
for /f "usebackq tokens=6 delims= " %%g IN ('more %%a | findstr /n $ | findstr /b "4:"') do (
set var=%%g
echo %var%
)
)
pause

2 个答案:

答案 0 :(得分:0)

您可以在skip循环中使用for /f选项直接在右行,找到该单词后,我们使用goto命令来中断循环:

@echo off

for %%a in (*.txt) do call:get6 "%%a"
echo done!!
exit/b

:get6

for /f "skip=3 tokens=6" %%b in ('type "%~1"') do (
    set "$6=%%b"
    goto:next
)
exit/b

:next
echo %$6%

编辑:

@stephan注释后,这里是使用原始findstr /n方法的相同代码:

@echo off

for %%a in (*.txt) do call:get6 "%%a"
echo done!!
exit/b

:get6

for /f "tokens=6" %%b in ('type "%~1" ^| findstr /n $ ^| find "4:"') do (
    set "$6=%%b"
    goto:next
)

exit/b

:next
echo %$6%

答案 1 :(得分:0)

这是在cmd.exe shell中执行此操作的另一种方法。

SET "FILELIST=D:yy\H Drive\subh\test\OUTPUT\*.*"

powershell -NoProfile -Command ^
    "Get-ChildItem -Path \"%FILELIST%\" |" ^
        "ForEach-Object {" ^
             "Get-Content -Path $_.FullName | Select-Object -Skip 5 -First 1 | ForEach-Object { ($_ -split '\s+')[5] }" ^
        "}"