【问题标题】:Powershell - Search and output line by linePowershell - 逐行搜索和输出
【发布时间】:2012-12-07 08:58:16
【问题描述】:

更新

我有一个包含一些参考的 1000 行日志文件。

Time Reference Date of start Date of end
12:00 AT001 13 November 2011 15 November 2011
13:00 AT038 15 December 2012 17 December 2012
14:00 AT076 17 January 2013 19 January 2013

$ref1 = AT038

基本上,我想解析日志文件并为 $ref1 输出(逐行),例如:

Time : 13h
Reference : AT038
Date of start : 15 December 2012
Date of end : 17 December 2012

提前致谢

【问题讨论】:

  • 编辑了我的答案以适应您的新信息
  • 这不是一个问题,它要求别人为你做这项工作。

标签: powershell output


【解决方案1】:

尝试:

$ref1 = "AT038"
$csv = Import-Csv .\myfile.txt -Delimiter ' '#Import file as CSV with space as delimiter
$csv | ? { $_.reference -EQ $ref1 } | FL #Piping each line of CSV to where-object cmdlet,  filtering only line where value of column reference is equal to $ref1 variable value. Piping the result of the filtering to file-list to have output as requested in OP.

在必要条件后添加的代码在 OP 中发生了更改:

$ref1 = "AT038"
$txt = gc .\myfile.txt
$txt2 = $txt | % { $b = $_ -split ' '; "$($b[0]) $($b[1]) $($b[2])_$($b[3])_$($b[4]) $($b[5])_$($b[6])_$($b[7])" }
$csv = convertfrom-csv -InputObject $txt2 -Delimiter ' ' 
$csv | ? { $_.reference -EQ $ref1 } | FL 

【讨论】:

  • 一些解释将有助于这个答案
【解决方案2】:

这个怎么样:

Get-Content SourceFileName.txt | 
% { ($_ -Replace '(\d{2}):\d{2} (\w{2}\d{3})', 'Time : $1h|Reference : $2').Split('|')} |
Out-File TargetFileName.txt

【讨论】:

  • 对不起,我忘了告诉你们,我的日志中有更多列,我刚刚更新了我的第一篇文章。谢谢!
【解决方案3】:

这是我的修改版:

$regex = '(\d{2}):\d{2} (\w{2}\d{3}) (\d{2} \b\w+\b \d{4}) (\d{2} \b\w+\b \d{4})'
$replace = 'Time : $1h|Reference : $2|Date of start : $3|Date of end : $4'
Get-Content SourceFileName.txt | 
% { ($_ -Replace $regex, $replace).Split('|')} |
Out-File TargetFileName.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多