How do I insert a filename into a text file?

February 8, 2011 at 15:26:27
Specs: Windows Vista
I have a number of .txt files and need to insert the filename of each into the first line and add a couple of line breaks. So I need some kind of loop on *.txt and to echo the filename at the top of the text file. Can anyone advise on how to do this with a DOS batch file or vbscript? Thanks.

See More: How do I insert a filename into a text file?

Report •


#1
February 8, 2011 at 19:21:55
Try this:

@ECHO OFF
SETLOCAL EnableDelayedExpansion

FOR /f "tokens=*" %%a IN ('DIR /b /a-d "*.txt"') DO (
ECHO %%a>>TempFile.txt
ECHO.>>TempFile.txt
TYPE %%a >>"TempFile.txt"
DEL %%a
REN "TempFile.txt" "%%a"
)
PAUSE

Can I put a question here?


Report •

#2
February 9, 2011 at 10:27:36
Thanks, that works a treat! Would it be possible to remove the ".txt" file extension from the inserted filename?

Report •

#3
February 9, 2011 at 15:32:44
Absolutely there is.

@ECHO OFF
SETLOCAL EnableDelayedExpansion

FOR /f "tokens=*" %%a IN ('DIR /b /a-d "*.txt"') DO (
SET Var=%%a
ECHO !Var:~0,-4!>>TempFile.txt
ECHO.>>TempFile.txt
TYPE "%%a" >>"TempFile.txt"
DEL "%%a"
REN "TempFile.txt" "%%a"
)
PAUSE

Can I put a question here?


Report •

Related Solutions

#4
February 9, 2011 at 17:22:47
Thanks again, really appreciated. Sorry about this but just one last thing ... the script fails if there are spaces in the filename. Is there a way around this? For example, can we replace spaces with underscores to make the filenames DOS-compatible then do the reverse when pasting in the title?

Report •

#5
February 9, 2011 at 19:10:57
Try my edited post above, I left out a few quotes.

Can I put a question here?


Report •

#6
February 10, 2011 at 16:09:15
Thanks again.

Report •


Ask Question