Solved

parse a text file for wanted status

Posted on 2009-03-30
15
434 Views
Last Modified: 2012-06-21
Hi Experts,

I am trying to find a way to parse a text file and extract the information I want... but not sure as how to do it well.  I have a text file that would tell the status of some processes running on the computer, and I want to write a script to analyze it, so it can extract the process name and the status (2nd & 4th column) :  (pls see code section)

so far, I have come up with:

@Echo Off
For /f "tokens=2,4 delims= " %%a in (D:\file.txt) Do (
If "%%a"=="adminprogram" Echo %%a %%b > result.txt
If "%%a"=="guestprogramr" Echo %%a %%b >>result.txt
If "%%a"=="systemr" Echo %%a %%b >>result.txt
)

What I wanted to do above is to further extract the 2nd & 4th column information to a text file called "result.txt".  Then I will use a third party program to monitor the "result.txt"... when it finds "result.txt" contains the word "stopped" or "stopping", it'll raise an alert.

But the code above doesn't work, as the spaces in 1st column would offset the token I have in the loop... can anyone help with a better way to extract the information?  or how to fix up this batch file? Thank you very much.
# Example Text file for analyze

--------------------------------------

[1]Admin program                     adminprogram               0005      Running

[2]Guest program                      guestprogram               2528      Running

[3]System                                   system                         8451      Running

Open in new window

0
Comment
Question by:wingkchan
  • 5
  • 4
  • 3
  • +2
15 Comments
 
LVL 21

Expert Comment

by:AmazingTech
Comment Utility
Looks like you're wanting to monitor a service.

Perhaps VBS is a better total solution for you.

Check out:

http://www.experts-exchange.com/Programming/Languages/Q_24124499.html
0
 
LVL 2

Author Comment

by:wingkchan
Comment Utility
Thanks AmazingTech for your reference.  I think I can use that to monitor some other problems that I am facing.

But, my situation is a little different.  The processes that I want to check are not shown in Window's Services nor Task Manager.  I called them "sub processes"  that belongs an application.  To see whether these sub-processes are running, I will need to type a show status command on command prompt...  That's why I am trying to dump a output of the screen to a plain text, analyze the text file for processes that stopped, and with a 3rd party tool, to send out email alerts.  

Do you have any ideas that I can do this in a smarter way?  Actually I have been hunting around for text parser scripts, hoping to find some useful stuff... but not much luck so far.
0
 
LVL 16

Accepted Solution

by:
t0t0 earned 167 total points
Comment Utility
Please try the following:

@echo Off
(for /f "tokens=1-5 delims= " %%a in (file.txt) do (
   if "%%e"=="" (
      if %%b==system echo %%b %%d
   ) else (
      if %%c==adminprogram echo %%c %%e
      if %%c==guestprogram echo %%c %%e
   )
))>result.txt
0
 
LVL 10

Expert Comment

by:TCB1
Comment Utility
Give AutoIt a look. www.autoitscript.com

It's a useful tool to do things like you need.
0
 
LVL 21

Assisted Solution

by:AmazingTech
AmazingTech earned 167 total points
Comment Utility
How about using shift?

Beware of the order in your piping to result.txt
For /f "tokens=*" %%a in (D:\file.txt) Do CALL :GETLINE %%a

GOTO :EOF
 

:GETLINE

If "%4" NEQ "" SHIFT && GOTO GETLINE

If /i "%1"=="adminprogram" Echo %1 %2 %3 > result.txt

If /i "%1"=="guestprogram" Echo %1 %2 %3 >>result.txt

If /i "%1"=="system" Echo %1 %2 %3 >>result.txt

Open in new window

0
 
LVL 9

Assisted Solution

by:sda100
sda100 earned 166 total points
Comment Utility
You could use this .WSF script, which is intended for Nagios, but is actually just standalone.  Using the command below, it will return a list of services (with their short names) and you could then use the same command (or SC if you prefer) to query their status.  You don't have to worry about spaces then:

The script (download the ZIP):
http://www.nagiosexchange.org/cgi-bin/page.cgi?g=2384.html;d=1

The command to list all services:
cscript //NoLogo check_service.wsf /info

See example script below.  The sample output from my script looks something like this (but you can make it output ANYTHING you like:

OK: Link-Layer Topology Discovery Mapper is running.
OK: TCP/IP NetBIOS Helper is running.
: LTActSvs is NOT running.
OK: Windows Media Center Extender Service is running.
OK: Machine Debug Manager is running.
OK: Multimedia Class Scheduler is running.
OK: Windows Firewall is running.
: MSCSPTISRV is NOT running.
OK: Distributed Transaction Coordinator is running.
Steve :)

@echo off

SetLocal EnableDelayedExpansion

for /f "tokens=1,*" %%i in ('cscript //NoLogo check_service.wsf /info') do (

	if "%%i"=="Service:" (

		set ShortName=%%j

	) else (

		if "%%i"=="Description:" (

			set LongName=%%j

			cscript //NoLogo check_service.wsf %%j>nul

			if errorlevel 1 (

				echo : !LongName! is NOT running.

			) else (

				echo OK: !LongName! is running.

			)

		)

	)

)

Open in new window

0
 
LVL 2

Author Comment

by:wingkchan
Comment Utility
Thanks sda100 for the script... but in my case, I want to check some processes that doesn't show on Task Managers... this .wsf file sorts the output of services well... however, it can't show the processes of the application that I need to monitor.  but thank you!
0
Free Gift Card with Acronis Backup Purchase!

Backup any data in any location: local and remote systems, physical and virtual servers, private and public clouds, Macs and PCs, tablets and mobile devices, & more! For limited time only, buy any Acronis backup products and get a FREE Amazon/Best Buy gift card worth up to $200!

 
LVL 9

Expert Comment

by:sda100
Comment Utility
Does the check_process give you what you want?  Even though you might have to fiddle with the output like I did above?

http://www.nagiosexchange.org/cgi-bin/page.cgi?g=Detailed%2F2924.html;d=1

In your original output, can we assume that there will only be 1 space between words in the process description, and at least 2 spaces as a delimeter between columns?  If so, the following solution might work (as an example):

Steve :)

@echo off

SetLocal EnableDelayedExpansion
 

set inputfile="test.txt"
 

for /f "tokens=*" %%i in ('type %inputfile%') do (

    echo %%i|findstr /B "[">nul
 

	if not errorlevel 1 (

		for /f "tokens=2* delims=]" %%j in ("%%i") do (

			set myText=%%j

			set myText=!myText:  =#!
 

			for /f "tokens=1,2,3,4 delims=#" %%k in ("!myText!") do (

				set Name=%%k

				set Desc=%%l

				set id=%%m

				set Status=%%n

				

				echo !Name! : !Desc! : !id! : !Status!

			)

		)

	)

)

Open in new window

0
 
LVL 16

Expert Comment

by:t0t0
Comment Utility
What's wrong with my code ??? Does it not work ???



@echo Off
setlocal enabledelayedexpansion

(for /f "tokens=1-5 delims= " %%a in (d:\file.txt) do (
   if "%%e"=="" (
      if /i "%%b"=="system" echo %%b %%d
   ) else (
      if /i "%%c"=="adminprogram" echo %%c %%e
      if /i "%%c"=="guestprogram" echo %%c %%e
   )
))>result.txt
0
 
LVL 9

Expert Comment

by:sda100
Comment Utility
Hi t0t0:

Your code assumes a fixed number of 'words' per line.  As I understand, the 1st column is a description and could be any number of words.  Add this line to the text file, and retry your code:

        [4]Another System Program                   system                         8942      Running

That's why I made the assumption there would be more than one space between fields.

Steve
0
 
LVL 16

Expert Comment

by:t0t0
Comment Utility
I assume the following is true:

1) the right-most column will ALWAYS only contain ONE word: the status of the process

2) the 2nd column from the right will ALWAYS contain the process ID

3) the 3rd column from the right will ALWAYS contain ONE word: the name of the owner of the process

4) the column on the left will ALWAYS be prefixed with '[x]' - where x is any integer

5) every thing else immediately following the prefix and the 3rd column from the right is the process name and may comprise of a variable number of lexemes

Please try this batch file.



@echo Off
:Main
   setlocal enabledelayedexpansion
   for /f "tokens=* skip=2" %%a in (file.txt) do call :ProcessLine %%a
exit /b


:ProcessLine
   set Count=0
   
   :Loop
      set /a Count+=1
      set Lex%Count%=%1
      shift
   if not "%1"=="" goto :Loop

   set Status=!Lex%Count%!
   set /a Count-=2
   set Process=!Lex%Count%!
   echo %Process% %Status%>>result.txt
exit /b
0
 
LVL 16

Expert Comment

by:t0t0
Comment Utility
wingkchan

Was my previous reply helpful?
0
 
LVL 2

Author Comment

by:wingkchan
Comment Utility
Sorry for the late reply... I got carried away with other works that dropped in.  In the meanwhile, A teamate with better scripting experience is helping me to write vbscript files to monitor the process.  But I will still try to use the recommendations above to test them out when I have  more free time.  Thank you and truly appreciate the input.  Will let you know the outcome soon.  Thanks!
0
 
LVL 16

Expert Comment

by:t0t0
Comment Utility
AmazingTech
I didn't know any other way of contacting you. I hope you don't mind me sliding in like this.

I wonder if you could help me with a problem I have in ID: 24321396 regarding error messages. Thanks.
0
 
LVL 2

Author Closing Comment

by:wingkchan
Comment Utility
sorry guys, I totally forgot about this until now... thanks for all the contributions.  I didn't finish this task at last, as the programers found a way to do what they wanted. thanks
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Being a system administrator some time we require to do things remotely, one of them is installing software. Here I am going to tell you how to install software through wmic (Windows management instrument console). I am not at all saying that this i…
By default, Carbonite Server Backup manages your encryption key for you using Advanced Encryption Standard (AES) 128-bit encryption. If you choose to manage your private encryption key, your backups will be encrypted using AES 256-bit encryption.
To efficiently enable the rotation of USB drives for backups, storage pools need to be created. This way no matter which USB drive is installed, the backups will successfully write without any administrative intervention. Multiple USB devices need t…
This tutorial will walk an individual through the process of configuring basic necessities in order to use the 2010 version of Data Protection Manager. These include storage, agents, and protection jobs. Launch Data Protection Manager from the deskt…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now