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

こ雲淡風輕ζ 提交于 2019-12-11 13:14:32

问题


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


来源:https://stackoverflow.com/questions/11044146/use-batch-file-to-copy-first-6-lines-to-a-new-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!