Vlookup CSV合并使用批处理文件

时间:2019-04-17 22:00:39

标签: csv batch-file

  • Groups.txt:
HFM_E_AHSM_FinRpt_Coor,,,xABC,Native Directory  
HFM_E_AHSM_FinRpt_Coor,,,xDEF,Native Directory  
HFM_E_AHSM_FinRpt_Coor,,,xGHI,Native Directory  
  • Reviewer.txt:
HFM_E_AHSM_FinRpt_Coor,Test
  • 当前输出:
Test,xABC,Native Directory  
Test,xDEF,Native Directory  
Test,xGHI,Native Directory  
  • 所需的输出:
HFM_E_AHSM_FinRpt_Coor,Test,xABC  
HFM_E_AHSM_FinRpt_Coor,Test,xDEF  
HFM_E_AHSM_FinRpt_Coor,Test,xGHI  

想从 Groups.txt 获取相同数据,对 Reviewer.txt 执行vlookup并放置匹配数据< / strong>,进入第2列,然后输入x值。最后删除最后一列

@echo off
setlocal EnableDelayedExpansion

rem Load File1 as lookup table:
for /F "tokens=1,2 delims=," %%a in (Reviewer.txt) do (
set "filename=%%~a"
set "col1_2[!filename: =_!]=%%~b"
 )

rem Process File2:
for /F "tokens=1* delims=," %%a in (Groups.txt) do (
   set "filename=%%a"
   for /F %%f in ("!filename: =_!") do if defined col1_2[%%f] (
      echo !col1_2[%%f]!,%%b
     ) else (
      echo NoMatchingFilename,%%b
     )
  )

1 个答案:

答案 0 :(得分:0)

您的样本数据在Groups.txt的col1中不包含任何空格,
因此,不清楚为什么要进行字符串替换!filename: =_!

否则,您需要进行两项更改

  1. for /F "tokens=1* delims=,"中的星号不会再拆分其他列
    => for /F "tokens=1,2* delims=,"
  2. groups.txt的col1在%% a中,但在输出中丢失。

@echo off
setlocal EnableDelayedExpansion

rem Load File1 as lookup table:
for /F "tokens=1,2 delims=," %%a in (Reviewer.txt) do (
set "filename=%%~a"
set "col1_2[!filename: =_!]=%%~b"
 )

rem Process File2:
for /F "tokens=1,2* delims=," %%a in (Groups.txt) do (
    set "filename=%%a"
    for /F %%f in ("!filename: =_!") do if defined col1_2[%%f] (
        echo %%a,!col1_2[%%f]!,%%b
    ) else (
        echo NoMatchingFilename,%%b
    )
)

产量:

> SO_55736556.cmd
HFM_E_AHSM_FinRpt_Coor,Test,xABC
HFM_E_AHSM_FinRpt_Coor,Test,xDEF
HFM_E_AHSM_FinRpt_Coor,Test,xGHI

请注意,for /f仅将连续的分隔符视为一个。
如果groups.txt包含,,,之间的内容,则列数不匹配