用批处理方式写一个文本批量改名程序,要求用文件名加文本的第一行或有效行,如果第一行是空行,则顺延到第二行,做为新的文件名。我的文件目录是e:\books全集\books\找回\。我用AI帮我写了几个程序,没有一个运行成功的,求大神给看一下,错在那里。
第一个- @echo off
- setlocal enabledelayedexpansion
-
- pushd e:\books 全集\books\找回\
-
- for /f "delims=" %%i in ('dir /b *.txt') do (
- set "line=%%i"
- for /f "tokens=1* delims=:" %%a in ('findstr /n. "%%i"') do (
- if "%%a" neq "" (
- set "newname=%%i -!line!:~0,1!"
- ren "%%i" "!newname!"
- goto :break
- )
- )
- :break
- )
-
- popd
复制代码 第二个- @echo off
- setlocal enabledelayedexpansion
-
- set "sourceDir=e:\books全集\books\找回\"
- for %%f in ("%sourceDir%*.txt") do (
- set "newFileName=%%~nf"
- for /f "delims=" %%a in ('type "%%f" ^| findstr /b /c:"[^ ]"') do (
- set "newFileName=%%~na"
- goto rename
- )
- )
- :rename
- ren "%%f" "!newFileName!.txt"
- endlocal
复制代码 第三个- @echo off
- setlocal enabledelayedexpansion
-
- set "sourceDir=e:\books全集\books\找回\"
- set "ext=txt" REM 更改为你的文件扩展名
-
- for /r "%sourceDir%" %%f in (*.%ext%) do (
- set "filename=%%f"
- set "newname="
-
- for /f "tokens=*" %%a in ('type "%%f"') do (
- if "!newname!"=="" (
- echo %%a | findstr /c:" " > nul
- if errorlevel 1 (
- set "newname=%%a"
- )
- ) else (
- set "newname=%%a"
- goto :renamed
- )
- )
-
- :renamed
- if not "!newname!"=="" (
- ren "!filename!" "!newname!.%ext%"
- )
- )
-
- endlocal
复制代码 第四个- @echo off
- setlocal enabledelayedexpansion
-
- rem 指定文件目录
- set "directory=e:\books全集\books\找回\"
-
- rem 遍历目录中的文件
- for /f "delims=" %%f in ('dir /b /a-d "%directory%*.txt"') do (
- set "file=%%f"
- set "newName="
-
- rem 读取文件的第一行
- for /f "tokens=1* delims=:" %%a in ('findstr /n "^" "%directory%\!file!"') do (
- if "%%a" neq "1" (
- set "newName=!newName!%%b"
- goto rename
- )
- )
-
- rem 如果第一行是空行,读取第二行
- for /f "tokens=1* delims=:" %%a in ('findstr /n "^" "%directory%\!file!" 2^>nul') do (
- set "newName=!newName!%%b"
- goto rename
- )
-
- :rename
- ren "%directory%\!file!" "!newName!.txt"
- )
-
- pause
复制代码
|