Home > Blockchain >  Cannot extract version number of nginx using regex
Cannot extract version number of nginx using regex

Time:10-05

I am trying to extract out the version number of nginx by using regex on powershell. This is the code I tried.

(& nginx -v) -match "\d \.\d \.\d "

This does not seem to work. I tried a similar thing with node.

(& node -v) -match "\d \.\d \.\d "

In this case it spits out True and I do acquire the version number.

$Matches[0]     # 16.11.0

In fact I tried to match on the first character but it still didn't work.

(& nginx -v) -match "."

This does not spit out True or False as if I never passed the -match operator. I was also trying to match on the first line of the output and ended up with this line which does spit out something but it is False.

@(& nginx -v)[0] -match "."

I am using powershell version 5.1 and nginx version 1.23.1

What is so weird about nginx's output that powershell could not match on it? How can I get around this?

CodePudding user response:

You need to use

(& nginx -v 2>&1) -match "\d (?:\.\d ) "

That is, the version string is printed on the standard error stream. 2>&1 redirects it to standard output stream, and makes the text "regexable".

CodePudding user response:

Or it looks like the output of cmd is all to 1 [stdout] (vice versa is also true, cmd running powershell). Replace everything before the slash with nothing.

# normally goes to stderr [2] - 'nginx version: nginx/1.23.1'

(cmd /c nginx -v) -replace '.*/'

1.23.1
  • Related