Wednesday, May 7, 2008

Removing lines from the output of a command line program

In case you need to deal with command line programs, you sometimes face the following challenge: the programs return too much data!

For example, Xteq Systems offers GetOSVersion which returns the current Windows version you are using. However, it also contains an header line so the complete example output is this:

Xteq GetOSVersion 3.0 - Copyright (C) 2008 Xteq Systems - http://www.xteq.com/

You are using Windows Vista (6.0) with Service Pack 1, return code is 9
(PlatformID 2; Major: 6; Minor: 0; Build: 6001)

Not that big deal if you (as an human) reads that but in case you want to export this data into a text file with the following command:

XQGetOsVer.exe /B >%TEMP%\result.txt

you will also of course get the header line you do not want to have. However, these is an easy solution for this: the FOR command. I won't get into the details what you can do with it (a lot and if you are interested use "help FOR" inside the command shell), but to solve the current problem we can simply use these two lines:

del %TEMP%\result.txt
for /F "skip=3 delims=" %%i in ('XQGetOSVer.exe /B') do @echo %%i >>%TEMP%\result.txt

First, we delete the file RESULT.TXT and then we execute the FOR command with two special parameters: SKIP=3 indicates that the first three lines from the output of XQGetOSVer.exe should be skipped and thus, the header is removed. The option DELIMS= indicates that we do not have delimiters so we get every line as is.

The part of DO indicates what we want to do with the remaining lines and use the ECHO command to write them to RESULT.TXT. We are using >> to indicate that we will append to this file (hence the DEL command first) to make sure we get all lines, not just one.

The result is exactly what we wanted:

You are using Windows Vista (6.0) with Service Pack 1, return code is 9
(PlatformID 2; Major: 6; Minor: 0; Build: 6001)

No header, just the the data.

No comments:

Post a Comment