【问题标题】:PowerShell: Unable to Import-CSV with line breakPowerShell:无法使用换行符导入 CSV
【发布时间】:2014-04-21 09:43:37
【问题描述】:

像这样,我想将文本文件数据导入访问。数据内容示例如下:(example.txt)

ID | Name | Message | User
----------------------------
1 | Joe | This is a text, error message | admin
2 | Mary | No error message, ID number: 9182734 | normal-user
3 | Terry | This is a long text, long message. Product ID : 1234,
Tag ID : fhdj123, Please restart | admin

我使用-分隔符“|”作为分隔符,它适用于 ID 1 和 ID 2,但当涉及 ID 3 时,它将一直读取到“...product ID :1234”,然后停止。之后,它开始从“Tag ID”读取新行。正如你们所看到的“|”在 ID 3 的末尾没有关闭。我想知道如何用换行符读取字符串。请帮忙。

【问题讨论】:

    标签: powershell csv import delimiter


    【解决方案1】:

    修复您的 csv。需要引用包含换行符或分隔符的值。您还应该在导入前删除第 2 行(-----------------line)。

    例如

    ID | Name | Message | User
    1 | Joe | This is a text, error message | admin
    2 | Mary | No error message, ID number: 9182734 | normal-user
    3 | Terry | "This is a long text, long message. Product ID : 1234,
    Tag ID : fhdj123, Please restart" | admin
    

    进口:

    PS > import-csv -Delimiter "|" .\Desktop\test.csv 
    
    ID  Name   Message                                                    User       
    --- -----  --------                                                   ----       
    1   Joe    This is a text, error message                              admin      
    2   Mary   No error message, ID number: 9182734                       normal-user
    3   Terry  This is a long text, long message. Product ID : 1234,...   admin 
    

    您也可以在导入之前替换文件中的换行符,但我猜您需要按原样使用这些值。

    【讨论】:

    • 是的,这很容易解决我的问题,只需在消息换行符之间添加双引号。谢谢。
    【解决方案2】:

    您将不得不解析您的导入文件并将 coma 后跟换行符序列 替换为一个 coma。这可能是,`n,`r,具体取决于您的文件格式。 这应该可以解决问题:

    gc example.txt | Out-String | % { 
        $_.replace(",`r",",").replace(",`n",",") } | Set-Content example.txt
    

    然后运行你的import-csv

    PS D:\>Import-Csv example.txt -Delimiter "|"
    

    这将导致列的正确分配:

    ID                      Name                    Message                User
    ---                     -----                   --------               ----
    --------------------...
    1                       Joe                     This is a text, err... admin
    2                       Mary                    No error message, I... normal-user
    3                       Terry                   This is a long text... admin
    

    您还可以删除多个连字符以使文件更易于阅读。

    【讨论】:

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