Board logo

标题: [文本处理] [分享]批处理两两合并文件并取首行内容作为新文件名 [打印本页]

作者: Batcher    时间: 2021-9-27 17:47     标题: [分享]批处理两两合并文件并取首行内容作为新文件名

【问题】
在一个文件夹里,批处理合并001.txt + 002.txt 合并后的新文件重命名为001.txt里的第一行文字,合并003.txt + 004.txt 合并后的新文件重命名为003.txt里的第一行文字,合并005.txt + 006.txt 合并后的新文件重命名为005.txt里的第一行文字......
作者: Batcher    时间: 2021-9-27 17:47

test1.bat
  1. @echo off
  2. setlocal enabledelayedexpansion
  3. cd /d "%~dp0"
  4. set "NewFolder=合并结果"
  5. if not exist "%NewFolder%" (
  6.     md "%NewFolder%"
  7. )
  8. for /l %%i in (1001,2,1999) do (
  9.     set "FileA=%%~ni"
  10.     if exist "!FileA:~-3!.txt" (
  11.         set /a FileB=FileA+1
  12.         set /p NewFile=<"!FileA:~-3!.txt"
  13.         copy /b !FileA:~-3!.txt+!FileB:~-3!.txt "%NewFolder%\!NewFile!.txt"
  14.     )
  15. )
复制代码

作者: Batcher    时间: 2021-9-27 18:16

test2.bat
  1. @echo off
  2. setlocal enabledelayedexpansion
  3. cd /d "%~dp0"
  4. set "NewFolder=合并结果"
  5. if not exist "%NewFolder%" (
  6.     md "%NewFolder%"
  7. )
  8. set "n=0"
  9. for /f "delims=" %%i in ('dir /b /a-d *.txt') do (
  10.     set /a n+=1
  11.     set /a m=n%%2
  12.     if !m! equ 0 (
  13.         set FileMerge="!FileMerge!"+"%%i"
  14.         copy /b !FileMerge! "%NewFolder%\!NewFile!.txt"
  15.     ) else (
  16.         set "FileMerge=%%i"
  17.         set /p NewFile=<"%%i"
  18.     )
  19. )
复制代码

作者: qixiaobin0715    时间: 2021-9-27 20:41

  1. @echo off
  2. setlocal enabledelayedexpansion
  3. cd /d "%~dp0"
  4. set "NewFolder=合并结果"
  5. if not exist "%NewFolder%" md "%NewFolder%"
  6. for /f "delims=" %%i in ('dir /b /a-d *.txt') do (
  7.     if not defined n (
  8.         set /p NewFile=<"%%i"
  9.         set str=%%i
  10.         set n=true
  11.     ) else (
  12.         copy !str!+%%i "%NewFolder%\!NewFile!.txt"
  13.         set n=
  14.     )
  15. )
  16. pause
复制代码

作者: qixiaobin0715    时间: 2021-9-28 08:25

蹭个热度。通常情况下,如果路径中含有空格的话,执行dos命令时,含有空格的路径应当使用双引号。有2个命令可以例外,那就是标记路径的命令pushd和目录跳转命令cd,当它们后面含有空格路径时,可不加双引号直接使用。
作者: Batcher    时间: 2021-9-28 09:08

回复 5# qixiaobin0715


    老版本的系统里面不加双引号会出错
作者: qixiaobin0715    时间: 2021-9-28 21:20

回复 6# Batcher
win7 win10可以,没有xp系统。
作者: Batcher    时间: 2021-9-28 21:26

回复 7# qixiaobin0715


    除了PC系统,还有一些老的Server版本的系统也是需要加双引号的。




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