2015-06-09 47 views
1

我有一个看起来一个文本文件,日志这样裁剪选择字符串输出。

2 total number of add errors 

我有一个脚本,是

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

我不记得如何得到它只是显示号码。

有什么建议吗?

回答

0

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

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

See link

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}中的第二个数字。

1

您不需要将“获取内容”输入到select-string中,它可以直接从文件中选择,但我认为它的工作原理比较简洁,根本不使用select-string,因此您可以将测试并获得数:

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] } } 
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"