Solved Need a batch file to compare number ranges in text file

October 10, 2012 at 12:14:52
Specs: Windows 7
Hi all,

I need help writing a batch file that will look at a text file where each row contains a range of numbers, and looks to see if the next line's numbers are included in the previous. If it is, it would check to see if it fits completely within the previous range, or partially. It would then expand the range to the largest number.

An example is probably the best way to explain.

Example 1:

If I have a text file that contains:

01101-01107
01213-01324
01320-01407
01406-01515

The end result I'm looking for is:

01101-01107
01213-01515


Example 2:

01101-01107
01213-01324
01320-01407
01409-01515

The result:

01101-01107
01213-01407
01409-01515


I'm new to writing batch files, and I cannot, for the life of me, figure out how to accomplish this.

Any help or suggestions would be greatly appreciated!!


See More: Need a batch file to compare number ranges in text file

Report •


#1
October 10, 2012 at 19:53:06
✔ Best Answer
this seemed to work:

::===== begin script
@echo off & setlocal enabledelayedexpansion
for /f "tokens=1,2 delims=-" %%a in (g) do (
if not defined lft set lft=%%a
if not defined rt set rt=%%b
if %%a gtr !rt! (>>g.out echo !lft!-!rt! & set lft=%%a)
set rt=%%b
)
>> g.out echo !lft!-!rt!
::====== end script

I have a feeling it will fail at some future juncture of spacetime. I guess the sourcefile has been sorted somehow.


Report •

#2
October 10, 2012 at 21:16:45
@nbrane

Thank you so much! This was incredibly helpful. I ended up tweaking it ever so slightly, as I noticed that when the line below fell completely within the previous range, it would take the second right column value, even if it was less than the first.

Here's what I ended up with:

@echo off & setlocal enabledelayedexpansion
for /f "tokens=1,2 delims=-" %%a in (g) do (
if not defined lft set lft=%%a
if not defined rt set rt=%%b
if %%a gtr !rt! (>>g.out echo !lft!-!rt! & set lft=%%a)
if %%b gtr !rt! (set rt=%%b)
)
>> g.out echo !lft!-!rt!


It's now working perfectly, thank you!!


Report •
Related Solutions


Ask Question