用于删除最后11行CSV的批处理文件

时间:2017-02-13 19:14:18

标签: csv batch-file

我希望通过批处理文件删除我的.csv文件的最后11行(总是11行),最好不要创建新命名的文件。我找到了以下删除前3行,但我不知道如何修改此删除最后11行。任何想法?谢谢你的帮助!

@echo off
set "csv=MyFile.csv"
more +3 "%csv%" >"%csv%.new"
move /y "%csv%.new" "%csv%" >nul

3 个答案:

答案 0 :(得分:1)

以下代码段使用临时文件执行您想要的操作:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_CSV_FILE=%~1" & rem // (specify CSV file here; `%~1` is first argument)
set "_NUM_FRST=0"   & rem // (specify number of lines to remove from beginning)
set "_NUM_LAST=11"  & rem // (specify number of lines to remove from end)

rem // Count number of available lines in file:
for /F %%C in ('^< "%_CSV_FILE%" find /C /V ""') do set /A "COUNT=%%C"
set /A "COUNT-=_NUM_LAST"
rem /* Process file, regarding and maintaining empty lines;
rem    lines must be shorter than about 8190 bytes: */
> "%_CSV_FILE%.tmp" (
    set /A "INDEX=0"
    for /F "delims=" %%L in ('findstr /N "^" "%_CSV_FILE%"') do (
        set /A "INDEX+=1"
        set "LINE=%%L"
        setlocal EnableDelayedExpansion
        if !INDEX! GTR %_NUM_FRST% if !INDEX! LEQ %COUNT% echo(!LINE:*:=!
        endlocal
    )
)
rem // Overwriting original file:
> nul move /Y "%_CSV_FILE%.tmp" "%_CSV_FILE%"

endlocal
exit /B

以下方法不使用临时文件:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_CSV_FILE=%~1" & rem // (specify CSV file here; `%~1` is first argument)
set "_NUM_FRST=0"   & rem // (specify number of lines to remove from beginning)
set "_NUM_LAST=11"  & rem // (specify number of lines to remove from end)

rem // Count number of available lines in file:
for /F %%C in ('^< "%_CSV_FILE%" find /C /V ""') do set /A "COUNT=%%C"
set /A "COUNT-=_NUM_LAST"
rem /* Process file, regarding and maintaining empty lines;
rem    lines must be shorter than about 8190 bytes: */
set /A "INDEX=0"
for /F "delims=" %%L in ('findstr /N "^" "%_CSV_FILE%" ^& ^> "%_CSV_FILE%" rem/') do (
    set /A "INDEX+=1"
    set "LINE=%%L"
    setlocal EnableDelayedExpansion
    if !INDEX! GTR %_NUM_FRST% if !INDEX! LEQ %COUNT% >> "!_CSV_FILE!" echo(!LINE:*:=!
    endlocal
)

endlocal
exit /B

答案 1 :(得分:0)

这是一个简单的命令来计算文件中的行。

但是,我没有看到截断文件而没有写入单独的中间文件。

@echo off
for /F "delims=[]" %%a in ('find /N /V "" myFile.TXT') do set LINE_COUNT=%%a
echo %LINE_COUNT%

答案 2 :(得分:-3)

将行more +3 "%csv%" >"%csv%.new"替换为head -n -11 "%csv%" > "%csv%.new"