【问题标题】:Read file and insert delimiter in output file with PowerShell使用 PowerShell 读取文件并在输出文件中插入分隔符
【发布时间】:2018-11-05 18:44:10
【问题描述】:

我从@Kieranties 中找到了以下代码,这对我来说非常有效,只是我的输入文件在第一行中不包含日期。

输出文件没有输入日期(没关系),也没有在第一行输入管道分隔符。所有其他行都是完美的。

我尝试修改此代码,但没有成功。

Function Parse-CDRFileLine {
    Param(
        [string]$line
    )

    $pattern = "^(.{2})(.{2})(.{1})(.{2})(.{1})(.{1})\s*(.{15})(.{10})\s*(.{7})\s*(.{7})\s*(.{1})\s*(.{1})(.{1})(.{1})\s*(.*)$"
    if($line -match $pattern){ 
        $result = $matches.Values | select -first ($matches.Count-1)
        [array]::Reverse($result, 0, $result.Length)
        $result = $result -join "|"    
        $result
    }
}



Function Parse-CDRFile{
    Param(
        [string]$filepath
    )    

    # Read content, setting first line to $date, the rest to $content
    $date,$content = Get-Content $filepath    

    # Create the output file, overwrite if neccessary
    $outputFile = New-Item "$filepath.out" -ItemType file -Force

    # Add the date line
    Set-Content $outputFile $date

    # Process the rest of the content
    $content | 
        ? { -not([string]::IsNullOrEmpty($_)) } |
        % { Add-Content $outputFile (Parse-CDRFileLine $_) }
}

Parse-CDRFile "C:\input.txt"

【问题讨论】:

标签: powershell delimiter delimited


【解决方案1】:

我能够弄清楚。我必须从读取 $date,$content = Get-Content $filepath 的行中删除“$date”并完全删除该行。设置内容 $outputFile $date

最终代码是。

Function Parse-CDRFileLine {
    Param(
        [string]$line
    )

    $pattern = "^(.{2})(.{2})(.{1})(.{2})(.{1})(.{1})\s*(.{15})(.{10})\s*(.{7})\s*(.{7})\s*(.{1})\s*(.{1})(.{1})(.{1})\s*(.*)$"
    if($line -match $pattern){ 
        $result = $matches.Values | select -first ($matches.Count-1)
        [array]::Reverse($result, 0, $result.Length)
        $result = $result -join "|"    
        $result
    }
}



Function Parse-CDRFile{
    Param(
        [string]$filepath
    )    

    # Read content, setting first line to $date, the rest to $content
    $content = Get-Content $filepath    

    # Create the output file, overwrite if neccessary
    $outputFile = New-Item "$filepath.out" -ItemType file -Force


    # Process the rest of the content
    $content | 
        Where { -not([string]::IsNullOrEmpty($_)) } |
        Foreach { Add-Content $outputFile (Parse-CDRFileLine $_) }
}

Parse-CDRFile "C:\input.txt"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 2018-08-07
    相关资源
    最近更新 更多