简体   繁体   中英

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.

@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 SKIP ped. 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 ECHO ed, only the very first line selected from each file is echo ed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM