Insert Text to a TXT file based on Filename

October 19, 2011 at 05:03:43
Specs: Windows XP
I have a series of TXT files that are more or less transaction logs. I am trying to combine all of the files into a single file that can be brought into Excel. If I just copied them all together, the resulting data would appear redundant as some of the files have the same transactions.

Ideally, I am trying to insert the filename of the text file at the beggining of each line in the text file. This would then allow me to concatenate all the files together and still know exactly where each row came from.

Of course, if that can't be batched, I would certainly be able to make due with a batch that insert a specific string of text into each line a specific file.

I've seen some possible solutions with SED but I can't find any that would batch through a folder of TXT files, grab the filename and then insert it into each file.

I humbly request help from those who can work a FOR TOKENS command like a Pro.

Thank you!

See More: Insert Text to a TXT file based on Filename

Report •

October 19, 2011 at 09:56:12
This is close to what you need, but it is missing something that is escaping my memory at the moment. When you nest loops like this, you have to be careful with your variables. I'm hoping one of the batch script gurus will spot my error...

@echo on

setlocal enabledelayedexpansion

REM First thing we need to do is get a proper list of the files we are going to loop through

dir /b c:\directory > files.tmp

REM now we need a nested loop that will look at each file in files.tmp and echo the filename and the original line
for /f "tokens=*" %%a in (files.tmp) do (
set line1=%%a
for /f "tokens=*" %%b in ("c:\directory\%line%") do (
set line2=%%b
echo %line1% %line2% > "c:\directory\%line1%"

Report •
Related Solutions

Ask Question