Search code examples
windowsbatch-filedos

batch to copy third line of multiple text files into a new text file and append original filenames to each line


In the following thread:

batch to copy last line of several .txt files into 1 new .txt file and appends file name on new line

...dbenham offered a solution to another poster, which works perfectly for my needs.

    @echo off
setlocal enableDelayedExpansion
>output.txt (
  for %%F in (*.log) do (
    <nul set /p "=%%F: "
    for /f %%N in ('type "%%F"^|find /c /v ""') do set /a skip=%%N
    if !skip! gtr 0 set /a skip-=1
    more +!skip! "%%F"
  )
)
type output.txt

My question: Can the syntax above be modified to copy the THIRD line of each *.txt file in the directory, append the filename of each file to the line, and send the results to a new output file?

Thanks kindly.


Solution

  • @ECHO OFF
    SETLOCAL
    (
     FOR %%f IN (*.log) DO (
      SET output=Y
      FOR /f "usebackqskip=2delims=" %%i IN ("%%f") DO IF DEFINED output (
      SET "output="
      ECHO %%f : %%i
      )
     )
    )>output.txt
    GOTO :EOF
    

    This will generate the output file containing the third non-blank line from each .LOG file, preceded by that file's name and a colon. The fix to do the same to .txt files should be obvious.

    One caution though - the created output file should NOT have the same extension as the files being processed.

    Normally, the FOR/F will output every line after those SKIPped. By adding the gate on the output variable, setting it to something before each target file is scanned then clearing it when the third line is ECHOed, only the very first line selected from each file is echoed.