[英]Batch script find and replace
我有一个批处理脚本,正在使用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 off @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软件包。 先感谢您
@echo off
setlocal EnableDelayedExpansion
findstr "Reply" %pingfile% >> %textfile%
for /F "tokens=1*" %%a in (%textfile%) do (
set rest=%%b
echo %%a !rest: =,!
)
这是上面的例程,在分隔的块中进行了一些更改:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.