我正在通过批处理文件运行curl并将输出打印到文本文件。 我想将此文本文件的最后一行复制到另一个文件,所以我会有类似的东西:
第一个档案:
0 594M 0 1017k 0 0 813k 0 0:12:27 0:00:01 0:12:26 813k
0 594M 0 2735k 0 0 1215k 0 0:08:20 0:00:02 0:08:18 1215k
0 594M 0 5074k 0 0 1561k 0 0:06:29 0:00:03 0:06:26 1561k
1 594M 1 6716k 0 0 1580k 0 0:06:25 0:00:04 0:06:21 1580k
1 594M 1 8027k 0 0 1489k 0 0:06:48 0:00:05 0:06:43 1566k
1 594M 1 8438k 0 0 1350k 0 0:07:30 0:00:06 0:07:24 1484k
1 594M 1 8883k 0 0 1225k 0 0:08:16 0:00:07 0:08:09 1229k
1 594M 1 9555k 0 0 1158k 0 0:08:45 0:00:08 0:08:37 896k
第二个档案:
1 594M 1 9555k 0 0 1158k 0 0:08:45 0:00:08 0:08:37 896k
批处理文件是:
curl -v -o NUL "http://...." 2>> file1.txt
timeout 10 /NOBREAK
copy /y file1.txt file1.tmp.txt 1>nul
setLocal EnableDelayedExpansion
for /f "tokens=* delims=" %%a in (file1.tmp.txt) do (
set var_file1=%%a
)
echo !var_file1!
echo !var_file1! > file2.txt
问题是第一个回显线打印最后一行,但第二行将整个 file1复制到file2。
为了只将file1的最后一行复制到file2,我应该更改什么?
谢谢!
答案 0 :(得分:0)
我能想到你的代码给出你所描述的结果的唯一情况是你接收的文件(file1.txt)是否使用单个回车符(\ r,0x0D)作为行终止符。
如果文件使用\ r作为行终止符并且文件永远不包含!
,则文件始终为< ~8190字节长,那么您可以使用以下代码获取最后一行:
@echo off
setlocal enableDelayedExpansion
curl -v -o NUL "http://...." 2>> file1.txt
:: I don't see why this line is here, but it shouldn't do any harm
timeout 10 /NOBREAK
:: Read each line and store in a variable - Only the last line is preserved
:: If the file uses CR as a line terminator, then the entire file is stored
:: Maximum variable length is ~8190 bytes
for /f delims^=^ eol^= %%A in (file1.txt) do set "s=%%A"
:: Define CR as a carriage return
for /f %%A in ('copy /Z "%~dpf0" nul') do set "CR=%%A"
:: Define LF as a line feed
set ^"LF=^
^" This and the above empty line are critical - DO NOT REMOVE
:: The following is only needed if CR is the line terminator
:: But this does no harm if we already have the last line
for %%A in ("!CR!") do for %%B in ("!LF!") do (
%= Remove existing LF =%
set "s=!s:%%~B=!"
%= Convert CR into LF =%
set "s=!s:%%~A=%%~B!"
)
:: Get the last line for sure
for /f delims^=^ eol^= %%A in ("!s!") do >test2.txt set "s=%%A"
:: Write the output file
>file2.txt echo(!s!
使用额外的代码可以消除文件中没有!
的限制,但有更好的方法。
使用我的JREPL.BAT regular expression text processing utility可以获得强大而有效的解决方案。 JREPL.BAT是一个混合JScript /批处理脚本,可以在XP以后的任何Windows机器上本机运行。
下面的代码假定JREPL.BAT位于当前文件夹中,或者更好的是,在PATH中列出的文件夹中。它适用于使用\ r,\ n,\ r \ n或\ n \ r \ n作为行终止符的文件。
@echo off
curl -v -o NUL "http://...." 2>> file1.txt
:: I don't see why this line is here, but it shouldn't do any harm
timeout 10 /NOBREAK
call jrepl "([^\r\n]+)(\r\n|\n\r|\r|\n)?(?!.)" "$1" /m /jmatch /f file1.txt /o file2.txt
如果您不需要file1.txt,那么我相信您可以执行以下操作直接获得结果
@echo off
curl -v -o NUL "http://...." 2>&1 | jrepl "([^\r\n]+)(\r\n|\n\r|\r|\n)?(?!.)" "$1" /m /jmatch /o file2.txt