【问题标题】:Vlookup logic to create a folder for moving a report用于创建用于移动报表的文件夹的 Vlookup 逻辑
【发布时间】:2018-05-06 21:15:18
【问题描述】:

我有两个文件,比如 Report.csv Reference.csv

我想编写一个脚本,将引用报表文件名中的 Report-ID 并与 Reference 文件数据交叉引用以确定移动报表的文件夹位置。

例如:Report.csv

R-00001.csv

Reference.csv 中的数据如下:

ReportID CompanyName
R-00001  BB Trust
R-00002  AA Trust
R-00003  ZZ Trust
R-00004  Canada Inc.

在上面,我们可以看到 Report.csv 的文件名和 Reference.csv 中的第一个单元格值是相同的。

查找后,需要将 R-00001.csv 文件移至“BB Trust”文件夹

同样,对于每个报告文件,需要遵循相同的程序

请帮忙,这会简化我的工作

  echo off
  :: Gets the filenames to textfile
  dir /b "C:\Users\Reports\" > 
  reportnames.txt
  :: Compare two files to look for 
  the matching ReportID and get the 
  Companyname value from 
  Reference.csv & create a folder in 
  that name and move the report 
  files to that corresponding folder

  for /f "tokens=1" %%i in 
  (Reportnames.txt) do
  @findstr "%%i," Reference.csv >nul 
  & If errorlevel 0 if not
  errorlevel 1 (for /f "tokens=2" 
  %%m in ('findstr /i /L "%%i," 
  Reference.csv') do ( cd 
  C:\Users\Archive\ & mkdir 
  %%m))

【问题讨论】:

    标签: batch-file scripting command


    【解决方案1】:

    您的描述有些混乱,示例代码与问题描述不符,所以我选择按照代码进行。

    没有必要首先dir /B列表创建Reportnames.txt文件,然后然后处理这样的文件...您可以直接处理通过标准的for 命令列出文件名。

    查找与 ReportId 匹配的 CompanyName 的最简单、最直接的“查找逻辑”方法是通过 array(尽管您可能知道它为 associative array)。

    最后,使用the :: trick 代替rem 命令插入cmets 不是一个好主意(不管你看到多少这样的技巧的例子)。

    @echo off
    
    rem Next line is required to correctly process array elements in a FOR loop
    setlocal EnableDelayedExpansion
    
    rem Load the associative array from Reference.csv file
    for /F "skip=1 tokens=1*" %%a in (Reference.csv) do set "CompanyName[%%a]=%%b"
    rem Previous FOR is equivalent to these lines:
    rem set "CompanyName[R-00001]=BB Trust"
    rem set "CompanyName[R-00002]=AA Trust"    etc...
    
    rem Process the filenames
    for %%a in (C:\Users\Reports\*.*) do (
    
       rem Get the matching CompanyName for the ReportId
       set "folder=!CompanyName[%%~Na]!"
    
       if not exist "C:\Users\Archive\!folder!" md "C:\Users\Archive\!folder!"
       move "%%a" "C:\Users\Archive\!folder!"
    
    )
    

    如果您对某个命令有任何疑问,您可以查看使用/? 参数输入的命令描述;例如:set /?

    【讨论】:

      猜你喜欢
      • 2017-02-01
      • 2018-05-29
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多