Pregunta

I would like to set up a simple batch file that would loop through all the .txt files in a folder (the folder where the batch file is placed), and add the same heading line to each of those files. The heading line is defined in a separate text file.

So for example, let's say I have:

c:\SomeFolder\Headings.txt   
    --> I want to add this to the top of each of the text files in:

c:\SomeFolder\FolderWithTextFiles\
    --> ...by running the batch file:

c:\SomeFolder\FolderWithTextFiles\BatchFile.batch

Extra notes:
- No need to loop through subfolders

¿Fue útil?

Solución

Windows batch does not have a native command to edit a file in place (other than to append data to it). So for each file, you need to create a temporary file with the desired content and then delete the original and rename the temp to the original. The delete and rename can be accomplished with a single MOVE command.

@echo off
set "header=c:\SomeFolder\Headings.txt"
set "folder=c:\SomeFolder\FolderWithTextFiles"
set "tempFile=%folder%\temp.txt"
for %%F in ("%folder%\*.txt") do (
  type "%header%" >"%tempFile%"
  type "%%F" >>"%tempFile%"
  move /y "%tempFile%" "%%F" >nul
)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top