Solved Add Filename As First Line Inside Text File

August 2, 2013 at 23:50:32
Specs: Windows 7
Hi, I have about 3000 text file, I want to put every filename at the first line of the text file, can someone help me with this? Thank you

See More: Add Filename As First Line Inside Text File

Report •

#1
August 3, 2013 at 00:31:28
✔ Best Answer
Tested briefly

::====== script starts here ===============
:: put filename in first line of txt files
:: melon.bat 2013-08-03 14:20:30.89
@echo off > NEWFILE & setLocal enableDELAYedeXpansioN

:main
for /f "tokens=* delims= " %%a in ('dir/b *.txt') do (
call :sub1 %%a
)
goto :eof

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

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


Report •

#2
August 3, 2013 at 05:27:40
Thank you,

It's working except I forgot to mention something,

There is already a content inside the file, the script replace everything inside the file with the filename. I want to add it in the first line without replacing the content.

One more thing, I also want to exlude the extension.

message edited by sundaymelon


Report •

#3
August 3, 2013 at 11:15:14
M2's script seemed to work fine when I tested it. The file's content was appended to the file's name, as ordered. Here's another version using copy to dodge potential landmines in the text-stream:
::==== begin batchscript
@echo off
for %%a in (*.txt) do (
>x echo %%~na
copy x+"%%a">nul
move /y x "%%a"
)
::==== script ends. edited to fix long-file-name crappola 8-4-13

message edited by nbrane


Report •

Related Solutions

#4
August 3, 2013 at 22:49:43
Still not working for me, after I run the script, It create another file named "x" .

Report •

#5
August 4, 2013 at 11:16:03
Are your file's extensions ".TXT"? If not, what are they, and are they all the same? Other than that, I can't see any reason for failure. (my limited tests worked with both rendered scripts)

Report •

#6
August 4, 2013 at 14:36:01
I'd assume wrath of missing double quotes has struck again.

How To Ask Questions The Smart Way


Report •

#7
August 4, 2013 at 18:10:24
Ha ha!! "Spot-on" as usual Razor. At least, as far as leaping the next hurdle. I'll fix it in my previous post (since I should have thought of that and failed to), then I'm retiring from this thread.

message edited by nbrane


Report •

Ask Question