数据整合

时间:2013-10-16 02:54:58

标签: batch-file for-loop

我有两个文本文件,其中包含以下内容:

FILE1.TXT:

ProcessId  VirtualSize  
5752       74649600     
3932       76843610
1357       90215638
& so on....

FILE2.TXT:

Notepad.exe pid: 3932 Linux
Notepad.exe pid: 1357 Macos
Notepad.exe pid: 5752 Windows
& so on....

现在,我们可以看到两个文件中的进程ID是相同的(匹配的),因此我想生成一个统一的单个输出文件(在两个文件中匹配processId),该文件应包含以下内容:

Output.txt的:

Windows 74649600  
Linux  76843610
Macos  90215638 
& so on....

我在下面试过,它正在运行但没有得到所需的输出:

@echo off
(for /f "skip=1 tokens=1,2" %%a in (file1.txt) do (
for /f "tokens=5" %%c in ('find " %%a " ^< file2.txt ') do echo %%c %%b
))>Output.txt 

EDIT1: 如果我想用字符串永久修复/设置'Output.txt'的前两行,我应该添加什么:

This output is for first server
Applcation Memory(GB )

即:

Output.txt的:

This output is for first server
Applcation Memory(GB)
Windows  74649600  
Linux  76843610
Macos  90215638 
& so on....

2 个答案:

答案 0 :(得分:2)

你的第二个FOR应该是以下内容。 “tokens = 5”部分选择第5个标记,而不是其他任何标记。你需要令牌3和5。

(for /f "skip=1 tokens=1,2" %%a in (file1.txt) do (
    for /f "tokens=3,5" %%x in ('find " %%a " ^< file2.txt ') do echo %%b %%y
))

如果File1和File2很长,那么该脚本可以正常运行但速度很慢。 我编写了一个脚本,重新格式化了file1和file2,使PID成为每行的第一件事。 然后,使用SORT通过PID组织文件。 最后,扫描已排序的输出,查找具有匹配PID的行对。

有点长,但很容易看出它是如何工作的。

@echo off
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

set INPUT1=file1.txt
set INPUT2=file2.txt
set OUTFILE=Outfile.txt
set TMPFILE=OutfileTMP.txt
set OUT=^>^>%OUTFILE%

if exist %OUTFILE% del %OUTFILE%
if exist %TMPFILE% del %TMPFILE%

call :ReadFile1
call :ReadFile2

sort < %OUTFILE% > %TMPFILE%
del %OUTFILE%
echo This output is for HFM server%OUT%
echo Applcation Memory(GB )%OUT%

set LASTPID=-
set LASTSIZE=-

for /f "tokens=1,2,3" %%a in (%TMPFILE%) do (
    if "%%b"=="1" set LASTPID=%%a&set LASTSIZE=%%c
    if "%%b"=="2" (
        if "%%a"=="!LASTPID!" (
            echo %%c !LASTSIZE! %OUT%
        ) else (
            echo Error: Not Matched: 1:!LASTPID!,!LASTSIZE!, 2:%%a %%c
        )
    )
)

del %TMPFILE%

goto :EOF


:ReadFile1
    for /f "skip=1 tokens=1,2" %%a in (%INPUT1%) do echo %%a 1 %%b %OUT%
    goto :EOF

:ReadFile2
    for /f "tokens=3,5" %%a in (%INPUT2%) do echo %%a 2 %%b %OUT%
    goto :EOF

答案 1 :(得分:2)

怎么样:

@echo off

echo This output is for HFM server > out.txt
echo Applcation Memory(GB) >>out.txt

for /f "skip=1 tokens=1,2" %%a in (file1.txt) do (
   for /f "skip=2 tokens=5" %%c in ('find " %%a " file2.txt 2^>nul') do ( 
     echo %%c %%b >>out.txt
  )
) 

相关问题