我想使用批处理文件删除“Data”目录中多个文件中的所有空行。我不想重命名文件。
我看过这篇文章,但由于以下原因,它没有帮助:How to delete blank lines from multiple files in a directory: *文件已重命名 *文件必须与.bat文件位于同一目录中
如果您还可以解释批处理文件命令,那将非常感激。
感谢。
答案 0 :(得分:1)
我决定将所有解释都包含在评论中。有一些方法可以在没有重命名/移动操作的情况下执行此操作,但不如此可靠。无论如何,最后,文件将具有相同的名称,但没有空行。
@echo off
setlocal enableextensions disabledelayedexpansion
rem There are some problems with references to batch files
rem that are called with quotes. To avoid the problems, a
rem subroutine is used to retrieve the information of
rem current batch file
call :getBatchFileFullPath batch
rem From the full path of the batch file, retrieve the
rem folder where it is stored
for %%a in ("%batch%") do set "folder=%%~dpa"
rem We will use a temporary file to store the valid
rem lines while removing the empty ones.
set "tempFile=%folder%\~%random%%random%%random%"
rem For each file in the batch folder, if the file is
rem not the batch file itself
for %%a in ("%folder%\*") do if /i not "%%~fa"=="%batch%" (
rem Now %%a holds a reference to the file being processed
rem We will use %%~fa to get the full path of file.
rem Use findstr to read the file, and retrieve the
rem lines that
rem /v do not match
rem /r the regular expression
rem /c:"^$" start of line followed by end of line
rem and send the output to the temporary file
findstr /v /r /c:"^$" "%%~fa" > "%tempFile%"
rem Once we have the valid lines into the temporary
rem file, rename the temporary file as the input file
move /y "%tempFile%" "%%~fa" >nul
)
rem End - Leave the batch file before reaching the subroutine
exit /b
rem Subrotutine used to retrieve batch file information.
rem First argument (%1) will be set to the name of a variable
rem that will hold the full path to the current batch file.
:getBatchFileFullPath returnVar
set "%~1=%~f0"
goto :eof
未注释的版本
@echo off
setlocal enableextensions disabledelayedexpansion
call :getBatchFileFullPath batch
for %%a in ("%batch%") do set "folder=%%~dpa"
set "tempFile=%folder%\~%random%%random%%random%"
for %%a in ("%folder%\*") do if /i not "%%~fa"=="%batch%" (
findstr /v /r /c:"^$" "%%~fa" > "%tempFile%"
move /y "%tempFile%" "%%~fa" >nul
)
exit /b
:getBatchFileFullPath returnVar
set "%~1=%~f0"
goto :eof