Board logo

标题: [文件操作] 批处理根据指定文本列出的新旧文件名对照列表批量重命名文件 [打印本页]

作者: jrx401    时间: 2016-6-28 11:47     标题: 批处理根据指定文本列出的新旧文件名对照列表批量重命名文件

本帖最后由 pcl_test 于 2016-7-4 10:34 编辑

[新手现丑了,如有不足,还请指点]
对应表格: list.txt(,前面为旧名,后面为新名称)
(实际上是无数个文本)
111111,32srfsdfa
222222,dff3afsaf
33333,rg4xvdzv
444444,wew34fsd
5555555,rtgfgxfbgd

当前文件夹有如下文本,需要依照以上对应表自动改名。
(实际上是无数个文本)
111111.txt
222222.txt
33333.txt
444444.txt
5555555.txt

[原创代码]:
  1. @echo off
  2. echo ---------------------------------
  3. echo REPLACE ALL THE FILE NAMEs by LIST.TXT
  4. echo The format of LIST.TXT should be below;
  5. echo Old Name,New Name
  6. echo                 ---by S.J a freshman of programmer
  7. echo ---------------------------------
  8. echo Press [y] and Enter key to backup the files before replacing.
  9. echo Press [n] and Enter key If you want to replace without backup.
  10. echo Yes or no?
  11. set "listfile=list.txt"
  12. for /f "tokens=2 delims==" %%i in ('wmic path win32_operatingsystem get LocalDateTime /value ^| find "="') do set datetime=%%i
  13. set now=%datetime:~,14%
  14. set input=
  15. set /p input=Please enter your choice[y/n]:
  16. :: Rename .txt and.pkg files
  17. for /f "tokens=1,2 delims=," %%i in ('type "%listfile%"') do (
  18.     if not exist "%%i.txt" (
  19.         if not exist Log_%now%.txt echo;non-existent files:>Log_%now%.txt
  20.         >>Log_%now%.txt echo;%%i_%%j
  21.     ) else (
  22.         if /i "%input%"=="y" (
  23.             md Backup%now%\ 2>nul
  24.             copy "%%i.txt" Backup%now%\
  25.         )
  26.         ren "%%i.txt" "%%j.txt"
  27.     )
  28. )
  29. cls
  30. if exist Log_%now%.txt type Log_%now%.txt
  31. pause
复制代码
[具体说明]:
1.刚开始按[y] enter key 可以备份原来的所有的txt文本
    (自动创建文件夹Backup20160628123320)
2. 对应表里面,没有更改到的文件,会以类似Log_20160628123320.txt档来记录。
作者: codegay    时间: 2016-6-28 12:39

用[/code]标签把代码圈起来。可读性更好。
作者: codegay    时间: 2016-6-28 12:40

把代码发代码区。不是这个版块。
作者: jrx401    时间: 2016-6-28 14:53

不好意思,怎样转移[发代码区]呢?
另外,[用[/code]标签把代码圈起来] 要怎样做呢?
作者: gawk    时间: 2016-6-28 19:30

第11行
set now=%date:~-10,4%%date:~-5,2%%date:~-2%%time:~0,2%%time:~3,2%%time:~6,2%
由于系统时间格式设置的不同,这里有可能获取到一个错误的字符串,甚至是包含 / 这个非法文件名的字符串。
作者: gawk    时间: 2016-6-28 19:31

第14行
if /i "%backup%"=="y"
建议加上 /i 忽略大小写
作者: gawk    时间: 2016-6-28 19:34

第24行
ren "%%i.txt" "%%j.txt"
两个ren应该是笔误吧。
文件名建议加上双引号,避免文件名包含空格等特殊字符导致命令出错。
作者: jrx401    时间: 2016-6-28 23:02

感谢 gawk 大虾 指点
作者: jrx401    时间: 2016-6-29 22:33

回复 5# gawk


    请问怎样不会让时间,出现这样的错误呢?
作者: gawk    时间: 2016-6-30 00:36

回复 9# jrx401


    参考 http://bbs.bathome.net/thread-3328-1-1.html




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