使用批处理逐行将信息附加到现有文件

时间:2015-02-06 14:42:09

标签: batch-file

我有一个查看报告(A.txt)的脚本并编译信息并将结果发送到新文件(B.txt)。脚本设置为每5分钟运行一次,报告(A.txt)在该时间范围内更改。我希望脚本能够将结果连接到每一行的右侧(可能用逗号分隔,但也可以只是一个空格,如果更简单),而不是在文件的底部。

这是我目前的剧本:

type A.txt | find "3," /c /i >> B.txt
type A.txt | find "48," /c /i >> B.txt
type A.txt | find "49," /c /i >> B.txt
type A.txt | find "50," /c /i >> B.txt
type A.txt | find "51," /c /i >> B.txt
type A.txt | find "52," /c /i >> B.txt
type A.txt | find "53," /c /i >> B.txt
type A.txt | find "201," /c /i >> B.txt
type A.txt | find "202," /c /i >> B.txt
type A.txt | find "311," /c /i >> B.txt
type A.txt | find "321," /c /i >> B.txt
type A.txt | find "332," /c /i >> B.txt
type A.txt | find "401," /c /i >> B.txt
type A.txt | find "402," /c /i >> B.txt
type A.txt | find "501," /c /i >> B.txt
type A.txt | find "502," /c /i >> B.txt
type A.txt | find "601," /c /i >> B.txt
type A.txt | find "701," /c /i >> B.txt

输出示例:

3,3
25,24
16,17
13,12
7,8
0,0
3,3
0,1
0,2
7,8
1,1
5,5
3,2
7,2
1,0
0,1
0,1
1,1

第3次迭代后,会有第3列有不同的结果。

2 个答案:

答案 0 :(得分:0)

@ECHO Off
SETLOCAL
SET /a line=0
DEL q28368239C.txt >NUL 2>nul
IF EXIST q28368239B.txt (SET "raw=") ELSE (SET "raw=Y")
FOR %%a IN (3 48 49 50 51 52 53 201) DO (
 FOR /f %%q IN ('type q28368239A.txt^|FIND /i /c "%%a," ') DO (
  IF DEFINED raw (>>q28368239C.txt ECHO(%%q
  ) ELSE (
   CALL :process %%q
   SET /a line +=1
  )
 )
)

MOVE /y q28368239C.txt q28368239B.txt >nul
TYPE q28368239B.txt

GOTO :EOF
:process
IF %line% neq 0 (SET "skip#=skip=%line%")
FOR /f "tokens=*%skip#%" %%b IN (q28368239B.txt) DO >>q28368239C.txt ECHO(%%b,%1&GOTO :eof
GOTO :eof

我使用名为q28368239A.txt的文件包含测试数据,q28368239B.txt表示输出数据,q28368239C.txt表示临时文件。

基本上,如果B文件不存在,则输出将为raw格式,即。仅限数字)

查找每个必需的字符串(我截断列表进行测试)并将计数分配给%%q

如果未找到%%q,则将B直接输出到临时文件,否则调用过程:process将计数%%q作为第一个参数,检查{{1}跳过0到%line%(行数)行(特殊:skip = 0不起作用)并将计数附加到现有行。

完成了!

注意:使用B作为数据项意味着文件中的任何33,命令中添加了,)将被视为{ {1}} - 这意味着FIND3以及3,等只是指出了......

答案 1 :(得分:0)

在这个解决方案中,我假设您不希望所有列中的每个查找的第一个数字,而只是在第一个...

@echo off
setlocal EnableDelayedExpansion

set "values=3, 48, 49, 50, 51, 52, 53,"

if not exist B.txt (

   rem Create B.txt for the first time
   findstr /L "%values%" test.txt > B.txt

) else (

   rem Join new values at right side of existent ones
   < B.txt (

      rem Get the new lines
      for /F "tokens=2 delims=," %%a in ('findstr /L "%values%" test.txt') do (
         rem Read an existent line
         set /P "line="
         rem Show old line and new value joined by a comma
         echo !line!,%%a
      )

   ) > B.new
   move /Y B.new B.txt > NUL

)