1

我有一个看起来像这样的文本文件日志

2 total number of add errors

我有一个脚本是

get-content "c:\logfile.txt | select-string "total number of add errors"

我不记得如何让它只显示数字。

有什么建议么?

4

4 回答 4

1

您可以使用 -match 和正则表达式来解析字符串:

get-content "C:\temp\test.txt" | select-string "total number of add errors" | Foreach{if ($_ -match "\d{1,5}") {$matches[0] }}

这将提取最多五位数的数字。{1,5}如果会有更大的数字,请更改第二个数字。

于 2015-06-09T15:28:07.063 回答
1

您不需要“获取内容”来输入选择字符串,它可以直接从文件中选择,但我认为它在不使用选择字符串的情况下工作得更整洁,因此您可以结合测试并获取数字:

gc logfile.txt |%{ if ($_ -match '^(\d+) total number of add errors') { $Matches[1] } }

如果你想尽量避免使用正则表达式部分,这个形状也适用于字符串拆分:

gc logfile.txt | % { if ( $_ -match 'total number of add errors') { ($_ -split ' ')[0] } }
于 2015-06-09T15:47:06.713 回答
0

假设您将始终拥有“x 添加错误总数”这一行,您可以将结果设置为字符串,然后从那里修剪它。

$newString = $firstString.Trim(" total number of add errors")

见链接

于 2015-06-09T15:09:44.173 回答
0

这可能是您正在寻找的:

#Get the file contents
$text = (Get-Content c:\test.txt)

#If you want to get an error count for each line, store them in a variable 
$errorCount = ""

#Go thru each line and get the count
ForEach ($line In $text)
{
   #Append to your variable each count
  $errorCount = $errorCount + $line.Substring(0,$line.IndexOf("total")).Trim() + ","
}

#Trim off the last comma
$errorCount = $errorCount.TrimEnd(',')

#Pint out the results in the console
Write-Host "Error Counts: $errorCount"
于 2015-06-09T16:59:49.610 回答