Italo Saraiva
Italo Saraiva

Reputation: 35

Batch to remove first line, Add filename to each line and merge TXT files

I've got a bunch of TXT files (nearly two hundred) to which I need to perform the following tasks:

  1. Remove the first line of text from each file;
  2. Add the filename(without extension) to the beginning to each remaining lines in the files;
  3. Merge all into one single TXT file.

I know that the following command will do the merging:

for %f in (*.txt) do type "%f">> output.txt

and this one adds a predefined text to the beginning of each line in a single txt file:

(for /f "delims=" %L in (filename.txt) do @echo sometext%L)>> output.txt

Any suggestions on how I could make it work? All help is appreciated. Thanks in advance.

Upvotes: 0

Views: 4866

Answers (3)

Aacini
Aacini

Reputation: 67206

This method eliminate the first line, preserve empty lines and insert the file name. I think it also should run faster:

@echo off
setlocal EnableDelayedExpansion

set "file="
(for /F "tokens=1* delims=:" %%a in ('findstr "^" *.txt') do (
   if "%%a" neq "!file!" (
      set "file=%%a"
   ) else (
      echo %%~Na:%%b
   )
)) > output.tmp
REM ren output.tmp output.txt

The output file is not named with .txt extension in order to avoid re-processing of its contents.

Upvotes: 3

Squashman
Squashman

Reputation: 14290

Assuming you are doing this all from the cmd prompt. Double the percent symbols if you want to run it from a batch file.

for %F in (*.txt) do for /f "skip=1 usebackq delims=" %L in ("%~F") do echo %~nF%L>> output.txt

Should you need it to keep empty or blank filled lines the second for loop changes to this.

FOR /F "skip=1 tokens=1* delims=:" %L in ('findstr /N /R "^" "%~F"') do echo %~nF%M>> output.txt

Upvotes: 0

Stephan
Stephan

Reputation: 56155

this removes empty lines, but also removes first lines and adds the filename to every line:

@echo off
>Output.txt (
for %%f in (*.txt) do (
  for /f "delims=" %%l in ('more +1 %%f') do (
    echo %%f:%%l
  )
))

Upvotes: 0

Related Questions