Solved How do I insert a filename into a text file?

August 23, 2014 at 17:30:26
Specs: Windows 7
I have a number of .txt files and need to insert the filename of each into the first and second line and add a couple of line breaks. So I need the fisrt part of the filename before ' - ' on the first line and text after ' - ' on the second line. Can anyone advise on how to do this with a DOS batch file ? Thanks.

Before:

Text in example - batch files.txt


I really need these text files to be
modified...Thank you!

After:

Text in example - batch files.txt


Text in example
batch files


I really need these text files to be
modified...Thank you!

I found this code on the forum by Matt123.It works great but everything stays on the first line in the text and I really don't know how to fix it to do the job.

@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


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

Report •


#1
August 24, 2014 at 01:50:43
I don't remember Matt132, but at my age there's plenty I don't remember.

Try this:

::====== script starts here ===============
::
:: MICK47.bat 2014-08-24 14:24:23.12
@echo off > NEWFILE & setLocal enableDELAYedeXpansioN

copy x\*.txt > nul

:main
for /f "tokens=* delims= " %%a in ('dir/b *.txt') do (
call :sub1 %%~Na
>> NEWFILE type "%%a"
move/y NEWFILE "%%a"
)
goto :eof

:sub1
for /f "tokens=1-2 delims=- " %%i in ("%*") do (
echo.%%i
echo.%%j
echo.
echo.
) >> NEWFILE
goto :eof
::====== script ends here =================

=====================
M2 Golden-Triangle


Report •

#2
August 24, 2014 at 14:48:47
Thank you for your help!I tried your code.It insert the first word of the filename in the first line and the second word in the second line.I'm trying to get the words before the ' - ' on the first and the words after this caracter on the second line.

Report •

#3
August 24, 2014 at 23:44:45
✔ Best Answer
:: Revised 13:42 25 August 2014
:: the original did not accomodate multi strings
:: on either side of the dash
::
::====== script starts here ===============
::
:: MICK47A.bat 2014-08-24 14:24:23.12
@echo off > NEWFILE & setLocal enableDELAYedeXpansioN

copy x\*.txt > nul

:main
for /f "tokens=* delims= " %%a in ('dir/b *.txt') do (
call :sub1 %%~Na
>> NEWFILE type "%%a"
move/y NEWFILE "%%a"
)
goto :eof

:sub1
for /f "tokens=1-2 delims=-" %%i in ("%*") do (
echo.%%i
echo.%%j
echo.
echo.
) >> NEWFILE
goto :eof
::====== script ends here =================

=====================
M2 Golden-Triangle


Report •

Related Solutions

#4
August 25, 2014 at 15:23:55
It works great! Thank you! You save me precious time...

Report •


Ask Question