Use batch file to copy first 6 lines to a new txt

2019-08-07 07:16发布

问题:

I have tried a dozen different ways and cannot get it right.

I have many text files in different folders, so I would like to reference the input file as a variable eg: *.txt (just use whatever txt file is in the same folder as the bat file).

I need to copy the first 6 lines and paste them into a new txt file.
I would like to name it (but not essential) SAMPLE_original_txt_file_name

EG:

Input = text01.txt
Output = SAMPLE_text01.txt (this would contain the first 6 complete lines from text01.txt)

I would appreciate any help as my head now needs stitches from banging it too much against a wall...

回答1:

The following worked for me:

@ECHO OFF
IF "%~1" == "" (ECHO Usage: %~nx0 filemask& GOTO :EOF)
FOR /F "delims=" %%I IN ('DIR /B %1') DO (
  <"%%I" (
    FOR /L %%I IN (1,1,6) DO (
      SET line=
      SET /P line=
      SETLOCAL EnableDelayedExpansion
      ECHO(!line!
      ENDLOCAL
    )
  ) >"%%~dpISAMPLE_%%~nxI"
)

The above script expects an argument, which is a file mask, like *.txt. It also supports masks completed with (existing) paths. Whether the path is specified or not, the output sample files are created in the same directory as the original ones.



回答2:

@echo off
set count=0
for /f "tokens=*" %%i in (text01.txt) do (
call :counter %%i
)
goto :eof
:counter
rem echo count is %count%
set /a count+=1
if %count% lss 7 echo %* >> SAMPLE_text01.txt
GOTO :eof