【问题标题】:Tailoring select-string output.定制选择字符串输出。
【发布时间】:2015-06-10 00:59:49
【问题描述】:

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

2 total number of add errors

我有一个脚本是

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

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

有什么建议吗?

【问题讨论】:

    标签: powershell select-string


    【解决方案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} 中的第二个数字。

    【讨论】:

      【解决方案2】:

      你不需要“get-content”来输入 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] } }
      

      【讨论】:

        【解决方案3】:

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

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

        See link

        【讨论】:

          【解决方案4】:

          这可能是您正在寻找的:

          #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"
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-02-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多