Board logo

标题: [文本处理] [已解决]如何使用BAT查找一个文件夹中是否存在指定开头的文件? [打印本页]

作者: chuyizhou    时间: 2014-1-8 13:25     标题: [已解决]如何使用BAT查找一个文件夹中是否存在指定开头的文件?

本帖最后由 chuyizhou 于 2014-1-13 13:56 编辑

大家好,

刚开始自学批处理,第一次发贴希望大家多多包涵。

我想使用bat实现一种功能,它能在指定的目录下查找由A.txt文件内包含的字符开头的文件,并且按照一定的格式输出。以下是我的一些逻辑,如果有不合适的地方请多多指教,谢谢!

Files list in folder: K:\x\y\z\
a1b1.txt
a1b2.txt
a2b1.txt
a2b2.txt
a3b.txt

A.txt的内容:
a1
a2
a4

若拿A.txt文件的内容去比较目标文件夹下面的文件,以下是期望的输出:

a1 --> a1b1.txt, a1b2.txt
a2 --> a2b1.txt, a2b2.txt
a4 --> null

然后因为a3b.txt在A.txt中没有参照,所以把它放到B.txt文件中。

因为工作需要,刚开始自学批处理,所以暂且把需求放上来希望可以得到解决。同时我也会用空闲的时间自学希望可以靠自己解决。

谢谢!
作者: terse    时间: 2014-1-8 15:52

本帖最后由 terse 于 2014-1-10 13:28 编辑

效率不理想
  1. @echo off&setlocal enabledelayedexpansion
  2. >$ dir /b /a-d K:\x\y\z\*.*
  3. for /f "delims=" %%i in (a.txt) do (
  4.     set "str="
  5.     for /f "tokens=*" %%j in ('findstr /ibc:"%%i"') do set str=!str!,%%j
  6.     if defined str (echo %%i  --^> !str:~1!) else echo %%i  --^> Null
  7. )
  8. >b.txt findstr /ivbg:a.txt $
  9. del $
  10. pause
复制代码

作者: cjiabing    时间: 2014-1-9 10:42

您的意思是指:指定一个搜索名称列表,并以此进行搜索?
作者: chuyizhou    时间: 2014-1-9 10:54

回复 3# cjiabing


   感谢您的回复! 是的,一个文件存的是一个列表,针对这个列表里的各个字搜索一个文件夹中是否有对应的文件。不知道又没有这样的可能性?
作者: chuyizhou    时间: 2014-1-9 11:18

回复 2# terse


    谢谢帮助!经过测试我得到了以下输出和文件的变动

cmd.exe的输出是:
The system cannot find the file 'findstr /ibc:"a1".
a1  --> Null
The system cannot find the file 'findstr /ibc:"a2".
a2  --> Null
The system cannot find the file 'findstr /ibc:"a4".
a4  --> Null
FINDSTR: Cannot read strings from a.txt
Press any key to continue . . .

检查a.txt文件发现其中的内容被删除,b.txt文件中没有内容。
请问您的代码中对a.txt和b.txt文件的存放位置有要求吗?是否和.bat文件在同一个目录下就可以了呢?
请不吝赐教!谢谢!
作者: terse    时间: 2014-1-9 14:47

回复 5# chuyizhou
代码不对A.txt文件作任何修改 所以a.txt应该是无改动的
另 for /f "tokens=*" %%j in ('findstr /ibc:"%%i" ) do set str=!str!,%%j
括号里应该这样 'findstr /ibc:"%%i"'  后面 似乎漏掉一个"'" 你检查一下再试
作者: cjiabing    时间: 2014-1-9 15:59

  1. @echo off
  2. for /f "" %%i in (a.txt) do (
  3. set /p= %%i --^> <nul
  4. for /f "tokens=4" %%a in ('dir /a *.txt^|findstr /ir "%%i"') do set /p= %%a, <nul
  5. echo;
  6. )
  7. pause
  8. for /f "tokens=4" %%a in ('dir /a *.txt^|findstr /irg:a.txt') do echo %%a
  9. pause
复制代码

作者: chuyizhou    时间: 2014-1-10 09:39

回复 7# cjiabing


    不好意思,我比较初级,似乎在代码里没有定义目标文件夹 K:\x\y\z,请问加在哪个循环里好呢?谢谢帮助!
作者: chuyizhou    时间: 2014-1-10 09:41

回复 6# terse


    加了"'"之后cmd.exe里什么都没有运行。请问这是什么原因?
作者: terse    时间: 2014-1-10 13:24

回复 9# chuyizhou
我这里测试正常
换个浏览器编辑下 (另:2楼重新编辑了)

检查代码第5行 是否一致
  1. for /f "tokens=*" %%j in ('findstr /ibc:"%%i"') do set str=!str!,%%j
复制代码

作者: cjiabing    时间: 2014-1-11 00:26

回复 8# chuyizhou


    直接放在这个文件夹里运行就可以了!
作者: chuyizhou    时间: 2014-1-13 13:53

回复 11# cjiabing


    谢谢!我改成tokens=5就好用了。可能是环境不一样我这儿dir出来文件名是第五块!非常感谢!
作者: chuyizhou    时间: 2014-1-13 13:54

回复 10# terse


    谢谢你哦!结合您和斑竹的代码最后有了我满意的coding。




欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2