batch file to read last four lines.

April 16, 2009 at 03:34:58
Specs: Windows XP

I've been doing some researching on the forum & I can't quite find the exact answer that I am looking for.

What I would like is to create a batch file to read the last four digits of a text file from the first line, then rename a .txt to the four digits that I just read from the file.

I've got a rough idea, but don't quite know how to put it all together...

Here is the information that i've gathered so far

something like this...

@echo off
echo "Read a line of text from a text file" >Text.txt
set /p var= <Text.txt
echo %var%

I know the above will only read

i am a bit of a newbie, so any pointers would greatly be appreciated!

See More: batch file to read last four lines.

Report •

April 16, 2009 at 03:57:00
@echo off
echo Read a line of text from a text file>Text.txt
set /p var=<Text.txt
set var=%var:~-4%
echo ren "sometextfile.txt" "%var%.txt"

Report •

April 16, 2009 at 04:50:59
super, I will give that a try & get back to you!

Report •

April 16, 2009 at 05:21:02
ok, that seems to do something, however my output is like this.

batch echo's

ren "file.txt" "    .txt"

it looks like its not reading the last four numbers from the file, however when doing some testing i took out everything from the source txt file and left four numbers & it then worked.

this is an example of the txt file first line


Report •

Related Solutions

April 16, 2009 at 05:29:46
ah, ok found the problem. it seems there is spaces at the end of txt file, is it possible to get the command to ignore these empty spaces?

Report •

April 16, 2009 at 05:38:59
if it helps, the string is always 28 characters long

Report •

April 16, 2009 at 08:50:01
This is a solution to lose trailing spaces. But it's not elegant.

@echo off > myfile.txt & setLocal EnableDelayedExpansion

for /f "tokens=* delims=" %%a in (infofile) do (
call :sub1 %%a
ren myfile.txt !str!.txt
goto :eof

set str=%1
set str=!str:~-4!
goto :eof

If at first you don't succeed, you're about average.


Report •

April 27, 2009 at 09:43:16
The following biterscripting script is an alternate solution.

var str text ; cat Text.txt > $text
var str line1 ; lex "1" $text > $line1
var str digits ; chex -e "[25" $line1 > $digits ; chex -e "[5" $digits > null
system ren myfile.txt $digits

First command line reads file Text.txt in variable $text. Second command line extracts the first line into $line1. Third command line extracts chars 25-28 into variable $digits. The last command line renames myfile.txt to the value of $digits.

If chars 25-28 will have a space in them, and you want to retain that space in the renamed file name, use ("\""+$digits+"\"") in the system command.

To try this, install biterscripting from . It is free. It seems to have more flexibility. And, its command are more conducive toward formulating a solution.


Report •

Ask Question