Windows awk-style functionality in batch script

0

I want to extract a word from a line in a test file on a Windows server, using batch script. The line of text is as follows;

 CURRENTHEIGHT(9182)     TEMPERATURE(1234) 

I would like to extract the number 9182 and 1234 which I need for some further computation.

How do I do this in a batch script?

Thanks

VNK

Posted 2016-10-19T20:29:26.443

Reputation: 11

1

Please note that https://superuser.com is not a free script/code writing service. If you tell us what you have tried so far (include the scripts/code you are already using) and where you are stuck then we can try to help with specific problems. You should also read How do I ask a good question?.

– DavidPostill – 2016-10-19T21:21:59.083

Hints: findstr - Search for strings in files. for /f - Loop command against the results of another command.

– DavidPostill – 2016-10-19T21:22:45.993

In Windows, you use awk exactly as in other OS. However, awk is not installed by default; you need to find and download a Windows package of posix utilities. – ddbug – 2016-10-19T22:11:34.243

Answers

1

If using Gnu-awk gawk is not an option you'll need a combination of the already mentioned for /f and findstr which has limited RegEx capabilities. for /f will ignore leading delimiters and treat consecutive delimiters as only one. To parse your sample line you need the delimiters () and space. The required numbers are tokens 2 and 4, tokens 1 and 3 are acceptable variable names. A RegEx for the line could be "CURRENTHEIGHT([0-9][0-9]*).*TEMPERATURE([0-9][0-9]*)" I DID say linmited ;-). The first used for variable %%A corresponds to the first token; %%D to the fourth one. To put all this together:

:: ExtractHeightTemp.cmd ::::::::::::::::::::::::::::::::::::::::::::
@echo off
Set File=C:\Test\test.txt
for /f "tokens=1-4 delims=() " %%A in (
  'findstr /i "CURRENTHEIGHT([0-9][0-9]*).*TEMPERATURE([0-9][0-9]*)" "%File%"'
) do Set _%%A=%%B&Set _%%C=%%D
Set _
Pause

The batch produces this output here:

> ExtractHeightTemp.cmd
_CURRENTHEIGHT=9182
_TEMPERATURE=1234

LotPings

Posted 2016-10-19T20:29:26.443

Reputation: 6 150