我有一个看起来像这样的文本文件日志
2 total number of add errors
我有一个
的脚本get-content "c:\logfile.txt | select-string "total number of add errors"
我不记得如何让它只显示数字。
有什么建议吗?
答案 0 :(得分: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 :(得分: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] } }
答案 2 :(得分:0)
假设您总是有“x add add of errors”,您可以将结果设置为字符串,然后从那里修剪它。
$newString = $firstString.Trim(" total number of add errors")
答案 3 :(得分: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"