开发者

powershell regular expressions

quick one:

$logFile="D:\Code\functest\1725.log"
function getTime($pattern) {
  Get-Content $logFile | %{ if ($_.Split('\t') -match $pattern) {$_} }
}
getTime("code")

gives me

simple  17-Feb-2011 10:45:27    Updating source code to revision: 49285
simple  17-Feb-2011 10:54:22    Updated source code to revision: 49285

but if I change the print value from

$_

to

$matches

I get nothing. I thought this array should have been created automatically? probably something silly, but this is my first day of using powersh开发者_StackOverflowell :-)

EDIT: what I want to return is

Get-Date (column 2 of the matching line)


Your call to Split() is using C# conventions to escape the t to specify a tab character. In PowerShell, you use a single backtick e.g. $_.Split("`t"). Also -match is behaving a bit differently on an array like this so have it operate on each individual string like so:

Get-Content $logFile | Foreach {$_.Split("`t")} | Where { $_ -match $pattern }

There's also a sort of hidden trick here with Get-Content where you can get it to split for you:

Get-Content $logFile -del "`t" | Where { $_ -match $pattern }

Update: based on the updated question, try something like this:

gc $logFile | % {$cols = $_.Split("`t"); if ($cols[2] -match $pattern) {$cols[1]}}

Keeping in mind that arrays are 0-based in PowerShell. If the text is already in a DateTime format that PowerShell/.NET understand, you can just cast it to a DateTime like so [DateTime]$cols[1].


The $_.Split('\t') is breaking it.
First, it's breaking on every letter "t", not at tabs. Second, it return a array that confounds -match.

With the following code:

Get-Content $logFile | %{ if ($_ -match $pattern) { $matches } }

getTime("code") would return:

Name                           Value                                                                                                                                       
----                           -----                                                                                                                                       
0                              code                                                                                                                                        
0                              code 

This would allow to search with regular expressions, as in

$answerArray = getTime("(\t)(\d+)")
$digitsOfSecondResult = $answerArray[1][2]
Write-Output $digitsOfSecondResult

If you just want to print the lines that match the pattern, try:

Get-Content $logFile | %{ if ($_ -match $pattern) { $_} }

To get the date:

function getTime($pattern) {
  Get-Content $logFile | %{ if ($_ -match $pattern) { Get-Date $matches[1] } }
}
getTime("`t(.+)`t.*code")

Or:

function getTime($pattern) {
  Get-Content $logFile | %{ if ($_ -match "`t(.+)`t.*$pattern") { Get-Date $matches[1] } }
}
getTime("code")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜