computing
  • 0

Solved Copy First & Last Lines From Multiple Files And Copy To New

  • 0

Hi,

Can you please help me

I am trying to Create a Batch file what would read multiple files from a folder and copy only the first and last lines from each file to a New text or csv file.

The file extension differs as some of them are .log and some are .txt

I Have 2 batch files that would read first and last lines separately but I am not able to combine them; so that I have the file name, first line and Last line in a single line with pipe delimiter;

Any pointers would greatly be appreciated!

Thanks to Various Post in this forum I was able to find the below code

Header Batch:::
(
for %%a in (*.txt) do (
set “first=”
for /f “usebackq delims=” %%b in (“%%a”) do if not defined first (
echo(“%%a |” %%b
set first=Y
)
))>%~DP0\Onlyheaderoutput.csv

Footer Batch::::
(
for %%F in (*.txt) 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”
)
)>> %~DP0\Onlyfooteroutput.csv

message edited by SridharCR

Share

1 Answer

  1. @echo off & setlocal EnableDelayedExpansion
    pushd YOUR DIRECTORY
    for %%i in (*.txt *.log) do (
      (set row=) & (set last=)
      for /F "delims=" %%j in ('type "%%i"') do (
        if not defined row (set row=%%i^|%%j) else (set last=^|%%j)
      )
      echo.!row!!last!
    ) >> result.csv
    popd
    

    • 0