检查文件存在并批量查找字符串错误

问题描述 投票:-1回答:3

我有一个批处理文件来查找文件。如果文件退出,则在这些文件中找到Request time单词。如果找到Request time字,我想输出FileName, "O"作为csv文件。如果找不到单词,则将FileName, "X"输出到csv文件。这是我的批处理脚本。

@echo off
Set "filePath=%~dp0"
:: Please change the filePath with your filePath.

if exist %filePath%nodes.txt goto Label1
echo.
echo Cannot find  %filePath%nodes.txt
echo.
Pause
goto :eof

:Label1
for /f %%i in (%filePath%nodes.txt) do call :check %%i
Pause
goto :eof

:check
Set "fOut=%filePath%pingRsl.csv"

if EXIST "%filePath%%1.txt" (
find "Request time" %filePath%%1.txt>nul
if %errorlevel% equ 1 (echo %1, O>>"%fOut%") else (echo %1, X>>"%fOut%")
) ELSE (
echo %1,"">>"%fOut%"
) 
goto :eof

但是,结果并不像我预期的那样。我无法弄清楚它的错误。

csv batch-file
3个回答
1
投票

我做了一些改动,(从:Label1开始),我希望他们帮助你。

:Label1
For /F "UseBackQ Delims=" %%A In ("%filePath%nodes.txt") Do Call :check "%%~A"
Pause
GoTo :EOF

:check
Set "fOut=%filePath%pingRsl.csv"

If Not Exist "%filePath%%1.txt" GoTo :EOF
(Find /I "Request time" < "%filePath%%1.txt" > Nul && (
      Echo %~1, O) || Echo %~1, X)>>"%fOut%"
GoTo :EOF

还要记住,虽然你暂时Set "filePath=%~dp0"它包括一个尾随斜线。因此,你需要确保你的最终用户,当他们:: Please change the filePath with your filePath.他们还包括一个尾随斜线,否则你将需要调整%filePath% %filePath%\的所有实例。


1
投票

标准的delayed expansion陷阱。使用顶部栏中的search工具查找delayed expansion以进行曝光。

简介:在执行块之前,代码块中的任何%var%(带括号的命令序列)都将替换为该变量的值。

所以

if %errorlevel% equ 1 (echo %1, O>>"%fOut%") else (echo %1, X>>"%fOut%")

应该

if errorlevel 1 (echo %1, O>>"%fOut%") else (echo %1, X>>"%fOut%")

这是if errorlevel的原始含义,表示运行时errorlevel是1还是大于1


0
投票

现在,我可以解决问题。

@echo off
Set "filePath=%~dp0"
:: Please change the filePath with your filePath.

if exist %filePath%nodes.txt goto Label1
echo.
echo Cannot find  %filePath%nodes.txt
echo.
Pause
goto :eof

:Label1
for /f %%i in (%filePath%nodes.txt) do call :check %%i
Pause
goto :eof

:check
Set "fOut=%filePath%pingRsl.csv"
if EXIST "%filePath%%1.txt" (
>nul find "Request time" "%filePath%%1.txt" && (
  echo %1,"X">>"%fOut%"
) || (
  echo %1,"O">>"%fOut%"
)
) ELSE (
echo %1,"">>"%fOut%"
) 
goto :eof
© www.soinside.com 2019 - 2024. All rights reserved.