本文介绍了解析具有备用文件名的多个文本文件,求和,然后使用批处理文件编译输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据用户建议进行了

我有一个脚本,可以在成千上万的服务器上运行,该脚本从日志中编译关键字,并输出它们在文本文件中出现的次数.每个服务器的输出如下所示:

I have a script that I run on thousands of servers that compiles keywords from logs and outputs how many times they occur within a text file. The output looks like this for every individual server:

---------- C:\TEMP\TEXT.001: 0
---------- C:\TEMP\TEXT.002: 0
---------- C:\TEMP\TEXT.003: 2
---------- C:\TEMP\TEXT.004: 0
---------- C:\TEMP\TEXT.005: 1

冒号后的最后一个数字是关键字在日志文件中的出现次数.因此,我有成千上万个服务器的结果文件,然后使用xcopy将文件移到同一文件夹中.

The last number after the colon is the number of times the keyword is present in the log file. So I have a result file from thousands of servers where I then utilize xcopy to move to my box into the same folder.

将文件移到我的盒子后,我有一个脚本,该脚本删除冒号之后的所有数据,然后找到总和.在某种程度上,它可以工作,但仅适用于单个文件:

After moving the files to my box, I have a script that removes all data after the colon, and then finds the sum. It works, to an extent, but it only works on a single file:


    @Echo off
    set "Total=0"
    for /f "tokens=3 delims=:" %%a in (Server1_Count.txt) do Set /a "Total+=%%a"
    (echo  %%a >> Server1_CountCompleted.txt Total is %Total%)

我遇到了两个问题:

  1. 我需要创建一个循环,该循环将命中同一文件夹中以* __ Count.txt结尾的每个文件,然后创建一个新的* _CountCompleted.txt输出.使用通配符无济于事. (即:server1_Count.txt,server2_count.txt然后应生成server1_CountCompleted.txt,server2_CountCompleted)
  2. 此脚本的当前输出只能定向到一个文件,它会生成一个新文件,如下所示:

是否可以添加要在新生成的文件中显示的主机名(文件名的开头前缀),例如:

Is there a way to add the hostname (beginning prefix of the file name) to be displayed in the newly generated file, an example:

推荐答案

仅使用set /a时,无需调用或延迟扩展.

When just using set /a no call or delayed expansion is neccessary.

提示:处理名称中可能包含空格的文件夹/文件时,最好使用冒号作为delim.

:: Q:\Test\2019\04\01\SO_55461444.cmd
@Echo off
set "Total=0"
for /f "tokens=3 delims=:" %%a in (FILE.txt) do Set /a "Total+=%%a"
echo Total is %Total%
pause

样本输出(德语区域设置):

Sample output (German locale):

> SO_55461444.cmd
Total is 3
Drücken Sie eine beliebige Taste . . .


给定文件夹中的新变体迭代文件*_count.txt:


New variant iterating files *_count.txt in given folder:

:: Q:\Test\2019\04\01\SO_55461444.cmd
@Echo off & SetLocal
:: clear/initialize env vars
set "Total=0"
for /F "delims==" %%A in ('set FileTotal[ 2^>nul') Do Set "%%A="

Pushd "X:\path\Folder" || (Echo couldn't change to folder &Pause&exit /b 1)

Echo Processing folder %CD%
Echo:
:: iterate files in folder
For %%F in (*_count.txt) Do (
    for /f "tokens=3 delims=:" %%A in (
        'Findstr "^-------" "%%F"'
    ) Do Set /A "FileTotal[%%~nF]+=%%A,Total+=%%A"
)

Set FileTotal[
Echo ===================
echo GrandTotal is %Total%
popd
pause

示例输出:

> Q:\Test\2019\04\01\SO_55461444.cmd
Processing folder Q:\Test\2019\04\02

FileTotal[server1_count]=3
FileTotal[server2_count]=15
===================
GrandTotal is 18
Drücken Sie eine beliebige Taste . . .

这篇关于解析具有备用文件名的多个文本文件,求和,然后使用批处理文件编译输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 14:10