Solved CMD How to read last line fr all available files in a folder

July 24, 2012 at 01:09:43
Specs: Windows XP
Hi, I have various text files (*.txt) in a folder. I want to read the last line from each text file one by one and output to a new text file. How can I do that without knowing all the file names?
Thanks!

See More: CMD How to read last line fr all available files in a folder

Report •

#1
July 24, 2012 at 02:08:22
✔ Best Answer
:: ===== script starts here ===============
::
:: amit.bat 2012-07-24 15:54:14.37
@echo off > newfile & setLocal enableDELAYedeXpansioN

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

goto :eof

:sub1
for /f "tokens=* delims= " %%a in (%1) do (
set S=%%a
)
>> newfile echo.!S!
goto :eof
::====== script ends here =================


====================================
Life is too important to be taken seriously.

M2


Report •

#2
July 24, 2012 at 02:54:53
Thanks a lot Mechanix2Go!
May I know why need to use setLocal enableDELAYedeXpansioN ? I tried to remove it and the code seems work the same way...

Report •

#3
July 24, 2012 at 03:13:43
"remove it and the code seems work the same way..."

I'd be very surprised. Maybe stunned is a better word.


====================================
Life is too important to be taken seriously.

M2


Report •

Related Solutions

#4
July 24, 2012 at 14:55:43
@ amitash I suppose its possible that your system has it set to enabled, for some reason. :D

:: mike


Report •

#5
July 24, 2012 at 20:28:44
Hi mates, I just removed the setLocal enableDELAYedeXpansioN and changed >> newfile echo.!S! to >> newfile echo.%S%
It really works the same way ... and I didn't do any extra settings in my system ...

:: ===== script starts here ===============
@echo off > newfile
for /f "tokens=* delims= " %%i in ('dir/b *.txt') do (
call :sub1 %%i
)

goto :eof

:sub1
for /f "tokens=* delims= " %%a in (%1) do (
set S=%%a
)
>> newfile echo.%S%
goto :eof
::====== script ends here =================


Report •

#6
July 24, 2012 at 21:20:52
enabledelayedexpansion is only needed when you need it (Lol!)
You can get by without it, but you need to know when, and when not.
M2's script happened not to need it, since the >>newfile echo statement was not inside (), so you're right. About 95% of the time, you will need it, but I like to "run lean" and only use when needed.
As for setlocal, only thing I can say, is if your script is completely uncooperative, check global ("environment") vars to see if any of your script var.s are showing up there. if they are, they can interfere with your intentions.

Report •

Ask Question