如何用Batch脚本移除TXT文件末尾空行并添加指定逗号
解决Batch脚本处理TXT末尾空行并添加逗号的问题
问题详情
需要给Ready.txt中最后一个数字行末尾添加逗号,但文件末尾存在空行,现有脚本会将逗号单独放在空行上方,无法达到预期格式。两种尝试的脚本均未成功:
尝试的脚本1
@echo off FOR %%i IN ("Toedit\Ready.txt") do ( findstr /V "^$" "%%i" >> "%%i.tmp" >>"%%i.tmp" echo , del "%%i" ren "%%i.tmp" "%%~nxi" )
尝试的脚本2
for /f "usebackq tokens=* delims=" %%a in ("Ready.txt") do (echo(%%a)>>~.txt move /y ~.txt "Ready.txt"
原始文件内容
"dfhg": [ 1, 2, 10, 4, 8, 9, 3, 6, 7, 5 ]
(注:末尾存在空行)
当前错误结果
"dfhg": [ 1, 2, 10, 4, 8, 9, 3, 6, 7, 5 , ]
期望结果
"dfhg": [ 1, 2, 10, 4, 8, 9, 3, 6, 7, 5, ]
解决方案
使用以下脚本,可在保留原文件空行结构的前提下,给最后一个非空行末尾添加逗号:
@echo off setlocal enabledelayedexpansion set "input=Toedit\Ready.txt" set "tempfile=!input!.tmp" :: 统计非空行总数,定位最后一个非空行 set "linecount=0" for /f "usebackq tokens=* delims=" %%a in ("!input!") do ( set /a linecount+=1 set "line!linecount!=%%a" ) :: 遍历所有行(含空行)并处理最后一个非空行 set "currentline=0" del "!tempfile!" 2>nul for /f "delims=" %%a in ('findstr /n "^" "!input!"') do ( set "fullline=%%a" :: 拆分行号与内容 for /f "tokens=1* delims=:" %%b in ("!fullline!") do ( set /a currentline=%%b set "content=%%c" :: 给最后一个非空行追加逗号 if !currentline! equ !linecount! ( echo !content!,>>"!tempfile!" ) else ( echo !content!>>"!tempfile!" ) ) ) :: 替换原文件 del "!input!" ren "!tempfile!" "!input!" endlocal
脚本说明
findstr /n "^"给每一行(包括空行)添加行号,完整保留原文件的空行结构- 两次遍历:第一次记录所有非空行,确定最后一个非空行的行号;第二次针对该行追加逗号
- 最终替换原文件,既完成逗号添加,又保留了原文件末尾的空行
内容的提问来源于stack exchange,提问作者JR Santos
相关产品推荐
相关产品推荐

