Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell ignoring look behind regular expression to return entire line

A simple enough question I hope.

I have a text log file that includes the following line:

123,010502500114082000000009260000000122001T

I want to search through the log file and return the "00000000926" section of the above text. So I wrote a regular expression: (?<=123.{17}).{11}

So when the look behind text equals '123' with 17 characters, return the next 11. This works fine when tested on online regex editors. However in Powershell the entire line is returned instead of the 11 characters I want and I can't understand why.

$InputFile = get-content logfile.log
$regex = '(?<=123.{17}).{11}'
$Inputfile | select-string $regex

(entire line is returned).

Why is powershell returning the entire line?

like image 877
user3046742 Avatar asked Apr 24 '15 15:04

user3046742


3 Answers

Don't discount Select-String just yet. Like Briantist says it is doing what you want it to but you need to extract the data you actually want in one of two ways. Select-String returns Microsoft.PowerShell.Commands.MatchInfo objects and not just raw strings. Also we are going to use Select-String's ability to take file input directly.

$InputFile = "logfile.log"
$regex = '(?<=123.{17}).{11}'
Select-string $InputFile -Pattern $regex | Select-Object -ExpandProperty  Matches | Select-Object -ExpandProperty Value 

Of if you have at least PowerShell 3.0

(Select-string $InputFile -Pattern $regex).Matches.Value

Which gives in both cases

00000009260
like image 171
Matt Avatar answered Nov 09 '22 13:11

Matt


It's because you're using Select-String which returns the line that matches (think grep).

$InputFile = get-content logfile.log | ForEach-Object {
    if ($_ -match '(?<=123.{17})(.{11})') {
        $Matches[1]
    }
}

Haven't tested this, but it should work (or something similar).

like image 43
briantist Avatar answered Nov 09 '22 13:11

briantist


You don't really need the lookaround regex for that:

$InputFile = get-content logfile.log
$InputFile -match '123.{28}' -replace '123.{17}(.{11}).+','$1'
like image 44
mjolinor Avatar answered Nov 09 '22 13:11

mjolinor