Board logo

标题: 关于随机变量%random% 求助 [打印本页]

作者: araise     时间: 2007-9-7 14:03    标题: 关于随机变量%random% 求助

我想实现把本文件夹内所有的文本文件改名,名字为随机数,用了%random%变量,程序如下:

@echo off
for %%a in (*.txt) do (ren %%a %random%.txt)

为何达不到预期效果,文本长名字的情况可用%~fsa解决,暂不考虑
在此for循环中,%random%不可更新,运行结果提示“与现有文件重名”
请问如何解决,实现对所有文件的随机更名操作

关键问题在与如何能在运行一次批处理的情况下生成若干个不同的随机数

[ Last edited by araise on 2007-9-7 at 02:41 PM ]
作者: Climbing     时间: 2007-9-7 15:49
试试这样:
@echo off
for %%a in (*.txt) do call :_rename "%%a"
goto :eof

:_rename
echo ren %1 %random%.txt
goto :eof
我自己没有测试,不知道好用不。

[ Last edited by Climbing on 2007-9-7 at 03:52 PM ]
作者: Climbing     时间: 2007-9-7 15:53
试过了,基本上满足要求。
作者: Climbing     时间: 2007-9-7 15:55
或者这样也可以:
@echo off & setlocal ENABLEDELAYEDEXPANSION
for %%a in (*.*) do echo ren "%%a" !random!.txt

作者: icyheart     时间: 2007-9-7 17:19
不对根本换不了只是写出来了不换
作者: araise     时间: 2007-9-7 20:04
Climbing你好,
你的第二段代码的思路我明白了,正是我所需要的,谢谢
只是第一段代码中有不解之处:
为何要在主程序段和标签中用到goto :eof
这个goto :eof我不很明白,之前也查过相关资料但仍不甚解
希望对此加以解释,谢谢
作者: Climbing     时间: 2007-9-10 09:19
:eof是一个默认标签,表示文件结尾(end of file),意思就是跳出程序。

其它的就好理解了吧?
作者: araise     时间: 2007-9-10 18:50
谢谢拉~~~
作者: kmtis003     时间: 2007-9-15 16:02


  Quote:
Originally posted by Climbing at 2007-9-7 03:55 PM:
或者这样也可以:
@echo off & setlocal ENABLEDELAYEDEXPANSION
for %%a in (*.*) do echo ren "%%a" !random!.txt

请讲解一下
@echo off & setlocal ENABLEDELAYEDEXPANSION
for %%a in (*.*) do echo ren "%%a" !random!.txt

中的setlocal这句和后面的ren "%%a" !random!.txt
是怎么来的.谢谢.看不懂~
作者: putao     时间: 2007-10-21 13:34
学习,谢谢
作者: 不得不爱     时间: 2007-10-22 17:47


  Quote:
Originally posted by kmtis003 at 2007-9-15 16:02:


请讲解一下
@echo off & setlocal ENABLEDELAYEDEXPANSION
for %%a in (*.*) do echo ren "%%a" !random!.txt

中的setlocal这句和后面的ren "%%a" !random!.txt
...

用FOR/?看下帮助