从特定目录中的多个文件中删除空行

remove blank lines from multiple files within a specific directory

我想用批处理文件删除"Data"目录下多个文件的所有空行。我不想重命名文件。

我看过这个 post,但没有帮助:How to delete blank lines from multiple files in a directory 原因如下: * 文件已重命名 * 文件必须与 .bat 文件位于同一目录中

如果您也能解释批处理文件命令,那将不胜感激。

谢谢。

我决定将所有解释都包含在评论中。有一些方法可以在不使用 rename/move 操作的情况下完成,但不如这个可靠。无论如何,最后,文件将具有相同的名称但没有空行。

@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