AWK Equivalent Functionality on Windows

I need to troubleshoot some issues on a client PC that I am unable to install additional software on and need some basic functionality of awk on windows xp & 7.

Basically, I need to strip the process ID from netstat so I can use it down the line in different parts of a script but have no knowledge of a native command that could do the equivalent of awk '{ print $4 }'. Are there any options for me? Obviously I'm quite new to windows cli.

3

4 Answers

To get the Process ID (PID):

  • open cmd.exe and type in:
  • tasklist /fi "imagename eq netstat.exe" > D:\test.txt

That command will create a new text file with the process ID of netstat (if netstat is running).
The problem is, that this file will contain more than only the PID.

Maybe its enough for you to start with?

2

For basic tasks like this, you can use for /f.

Instead of

command | awk '{ print $4 }'

try this:

for /f "tokens=4" %a in ('command') do echo %a

Note that you have to use %%a instead of %a in batch files.

Sample netstat -n -o output:

Active Connections Proto Local Address Foreign Address State PID TCP 127.0.0.1:12345 127.0.0.1:23456 ESTABLISHED 4321 TCP 127.0.0.1:34567 127.0.0.1:45678 ESTABLISHED 5432

To strip out the top 2 lines pipe the output to findstr /v "Active Proto".

To print only specific column data, for example the Local Address and PID, use:

for /f "tokens=2,5" %i in ('netstat -n -o ^| findstr /v "Active Proto"') do @echo Local Address = %i, PID = %j

If using in a batch file, you have to double the % signs, and can assign the values you want (%%i, %%j etc.) to variables.

1

Elaborating on @Dennis's answer, here is a snippet I used to extract a version number out of a C header file, and use it to create a new file name.

My header file looks like

 ... stuff #define FIRMWARE 8 .. stuff

The equivalent of UNIX

 f=`awk /FIRMWARE/ { print "image_v" $3 ".txt"; } project_config.` echo $f

in DOS is

 for /f "tokens=3" %%a in ('findstr FIRMWARE project_config.h') do ( set f=image_v%%a.txt ) echo %f%

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like