【问题标题】:Batch programing to search some file in sub folders批处理编程以搜索子文件夹中的某些文件
【发布时间】:2015-04-05 17:05:09
【问题描述】:
我有数百个 csv 文件。 csv文件存储在文件夹和子文件夹中。我想搜索五十个文件名已确定的 csv 文件,例如 1.csv 、 2.csv 、 3.csv 、 ... 、 50.csv 。如果我用Windows搜索工具一一搜索就很麻烦了。如果找到文件,我想保存在名为 FOUND 的文件夹中。请帮助通过使用批处理编程/蝙蝠来克服这个问题?非常感谢
【问题讨论】:
标签:
batch-file
search
directory
subdirectory
【解决方案1】:
可以采用多种方法,具体取决于您需要多少自动化...为了帮助您入门,您可能想查看this,它帮助了我(并且确实继续这样做)当我开始学习批处理。此外,正如我所解释的那样,我将提供一个可能的模板来实现您的目标。也许它不是最优雅或最有效的方法,但它引入了许多您可能遇到或可能没有遇到过的批处理命令,这反过来可能会帮助您开发自己的方法。
@echo off
setlocal enabledelayedexpansion
echo Please enter a drive letter:
set /p "drive=>"
echo Please enter a search string:
set /p "searchstring=>"
echo %searchstring%>search.txt
set /p search=<search.txt
set /a suffix=0
echo.>>search.txt
:LOOP
for /f "tokens=*" %%i in ("search.txt") do (
set /a suffix=suffix+1
set seq=%search% !suffix!
echo !seq!>>search.txt
)
if !suffix! leq 49 goto LOOP
for /f "tokens=*" %%i in (search.txt) do (
for /f "tokens=*" %%j in ('dir /b /s /a-d %drive%:\"%%i.csv" 2^>nul') do (
if not exist "%~dp0\found" md "%~dp0\found"
move /y "%%j" "%~dp0\found\%%~nxj"
)
)
pause
这并不是一个明确的解决方案,尽管您可能会发现它回答了您的原始查询/请求。一切顺利。
【解决方案2】:
这是另一个适合您的解决方案..
@ECHO OFF
SETLOCAL EnableDelayedExpansion
REM First Set your directories input and output
SET InputDir=C:\Directory to your CSV files\
SET OutputDir=C:\Directory to your CSV files\FOUND
REM check if the FOUND directory exist, if not, then create it.
IF NOT EXIST OutputDir (
mkdir %OutputDir%
)
REM Grab a scan of the input directory and save it to a temporary file list.
Dir /a /b %InputDir%>"%OutputDir%\Found.txt"
REM Set the files you would like to find.
SET "File1=1.csv"
SET "File2=2.csv"
SET "File3=50.csv"
REM The loop, to process the matching file(s).
FOR %%A IN (%File1%,%File2%,%File3%) DO (
FOR /F "usebackq" %%B IN ("%OutputDir%\Found.txt") DO (
IF %%A==%%B (
copy "%InputDir%\%%A" "%OutputDir%\%%A"
)
)
)
REM Clean up the temp file list.
DEL "%OutputDir%\Found.txt"
请注意,我没有在 Input 和 Output 变量中添加引号,而是在代码的复制部分添加引号以补偿目录路径中的空白。我尽量保持简单,所以你可以按照它如何处理你正在寻找的东西的逻辑,你现在可以根据自己的喜好修改它......玩得开心。干杯!