Extracting a Version Number From a Text File Using Batch Files and Cygwin

We have a version.h file. It contains lines such as:

#define VERSION_MAJOR     3
#define VERSION_MINOR     1

By piping this through grep, I can get the line I'm looking for:

c:\>grep "VERSION_MAJOR" version.h
#define VERSION_MAJOR     3

But what I really want is the version number within the line, so I pipe this through sed:

c:\>grep "VERSION_MAJOR" version.h | sed -e "s/^.* VERSION_MAJOR\s*\([0-9]\+\)/\1/g"
3

So now we have extracted the version number corresponding to "VERSION_MAJOR". However, in order to conditionally branch in our batch script, we need to get this value into an environmental variable. In bash, this would be accomplished with backticks. As it turns out, Windows batch files do provide similar functionality, but through a much clumsier means:

c:\>for /f "tokens=3" %i in ('grep " VERSION_MAJOR" version.h') do set MAJORVERSION=%i
c:\>echo %MAJORVERSION%
3

About Jeff Fitzsimons

Jeff Fitzsimons is a software engineer in the California Bay Area. Technical specialties include C++, Win32, and multithreading. Personal interests include rock climbing, cycling, motorcycles, and photography.
This entry was posted in Scripting, Technology. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *