Kiddo
Kiddo

Reputation: 1980

Merge multiple text files but skip first and last line of each file

I have a hundred of text files with the below structure:

file1.txt
Class Categeory_1 {
   (content 1, may contain many other block ending with }; )
};

file2.txt
Class Categeory_2 {
   (content 2, may contain many other block ending with }; )
};

I would like to merge all the files without the first and last line of each file, so the output.txt should be:

(content 1, may contain many other block ending with }; )
(content 2, may contain many other block ending with }; )
...

Files names are random, and class name are also random, but starting with "Category_"

I know how to merge all of the files together:

@echo off
    for /r %%i in (*.txt) do (
        if not %%~nxi == output.txt (
            copy /A output.txt+"%%i" && echo. >> output.txt
        )
    )

but not sure how to skip the first and last line of each file. Can you please provide some help, thank you.

Upvotes: 0

Views: 1854

Answers (1)

Monacraft
Monacraft

Reputation: 6630

Here is a working code sample

@echo off
setlocal enabledelayedexpansion

if exist output.txt del output.txt
set "var="
for /r %%i in (*.txt) do (
  if "%%~nxi" NEQ "output.txt" (
  set "var="
  for /f "usebackq skip=1 delims=" %%b in ("%%~i") do (
    if "!var!" NEQ "" Echo !var!
    set var=%%b
))) >> output.txt

Here's a quick summary of what it does:

  1. Setlocal allows the reference of updated variable values in the for-loop
  2. Delete an existing output and reset var variable
  3. For every text file, that is not output.txt
    1. Reset the value of var to nothing
    2. For every line in this text-file, skipping the first line:
    3. If var is not empty, echo its value
    4. Set the value of var to the current line

>> redirect all echo's into output.txt

Note, the order of the last 2 steps is what allows you to skip the last line since you are always echoing the previous line.

  • This means if the file only has 2 lines, it will not echo anything,

  • If it has 3 lines it will only echo the middle one,

  • And if it has 4 lines it will echo the middle two, etc.

Upvotes: 1

Related Questions