批处理脚本查找和替换

时间:2013-12-10 04:05:30

标签: windows batch-file replace find findstr

我有一个使用psping并将输出输出到文件的批处理脚本,如下所示

psping -l 8192 -i 1 -n 5 -w 0 localhost >> %outfile%

然后,我只是寻找具有“回复”的行,如下所示:

findstr /N "Reply" %outfile%

如您所知,获得的行格式如下:

Reply from <IP>: 8.59ms
Reply from <IP>: 9.18ms
Reply from <IP>: 8.82ms
Reply from <IP>: 9.40ms
Reply from <IP>: 8.81ms

然后我有这个用逗号替换空格的子程序

findstr "Reply" %pingfile% >> %textfile%
for /F "tokens=* delims= " %%a in (%textfile%) do @call :processeachline %%a
endlocal
goto :eof
:processeachline
setlocal
set data=%*
echo %data: =,%
endlocal
goto:eof

以上结果如下:

Reply,from,<IP>:,8.81ms

但我需要采用以下格式。

Reply from,<IP>,8.81,ms

整个代码如下     @echo关闭     @set local     echo日期为%DATE%

@set tag=%DATE:~-4%-%DATE:~7,2%-%DATE:~4,2%
set pingfile=psping%tag%.txt

echo file name:  %pingfile%

if exist %pingfile% (
echo deleting existing ping file...
del %pingfile%
)

set "tempfile=tempOut.txt"
set "newfile=csvOutput%tag%.txt"
if exist %tempfile% (
echo deleting existing temp output file...
del %tempfile%
)


echo Ping started at %DATE% %TIME% >> %pingfile%

REM Ping 5 times with an interval of 10 seconds between each with 0 warmup
psping -i 1 -n 5 -w 0 cnn.com >> %pingfile%



REM When done, parse the file and get only the necessary lines for the CSV
findstr "Reply" %pingfile% >> %tempfile%

REM parse the temp file and replace all spaces with commas and write to the csv
for /F "tokens=* delims= " %%a in (%tempfile%) do @call :processeachline %%a

goto :eof
:processeachline
set data=%*
echo %data: =,% >> %newfile%

for /F "tokens=*" %%a in ('findstr ms %newfile%') do @call :processeachlines "%%a"

goto :eof
:processeachlines
set data=%~1

echo %data:ms=,ms%

@endlocal

如何进行此操作(理想情况下无需打开%textfile%)?我必须使用标准的Windows工具,不能安装任何GNU包。 提前谢谢

2 个答案:

答案 0 :(得分:0)

@echo off
setlocal EnableDelayedExpansion

findstr "Reply" %pingfile% >> %textfile%
for /F "tokens=1*" %%a in (%textfile%) do (
   set rest=%%b
   echo %%a !rest: =,!
)

答案 1 :(得分:0)

这是你上面的例程,在分隔的块中有一些变化:

findstr "Reply" %pingfile% >> %textfile%
for /F "tokens=* delims= " %%a in (%textfile%) do @call :processeachline %%a
endlocal
goto :eof
:processeachline
setlocal
set data=%*

set data=%data: =,%
set data=%data::=,%
set data=%data:ms=,ms%
set data=%data:Reply,from=Reply from%

echo %data%
endlocal
goto:eof