首页 > 解决方案 > Powershell:在 CSV 文件中编辑所有换行符和回车符

问题描述

目标是删除所有单个“换行符”(LF),并将回车符(CR)后面的“换行符”保留在csv文件中。

我得到一份报告,其中包括一行中的多个 LF,但我只想保留“CR+LF”,因此每一行代表一个报告的对象。

我需要一个解决方案PowerShell,不幸的是我对 PowerShell 脚本非常陌生。我试图为这项工作更改这方面的一些脚本,但它不起作用。

首先,我会尝试删除文件中的所有 LF,然后将所有剩余的 CR 替换为[CR][LF]. 但我没有迈出第一步。

$original_file ='C:\Test\Server.csv'
$new_file = 'C:\Test\Server_changed.csv'
(Get-Content $original_file -Raw).Replace('´n',' ') | Set-Content $new_file -Force
(Get-Content $new_file -Raw).Replace('`r','`r`n') | Set-Content $new_file -Force

来源CSV

"Servername";"CPU","Memory";"Annotation";"OperatingSystem"[CR][LF]
"Server1";"4";"8";"very importand Server!![LF]
If reboot is needed:[LF]
1. Contact Me[LF]
2. Stop all running Services before shutting down the OS[LF]
";"Windows Server 2019";[CR][LF]

它应该看起来如何:

"Servername";"CPU","Memory";"Annotation";"OperatingSystem"[CR][LF]
"Server1";"4";"8";"very importand Server!! If reboot is needed: 1. Contact Me 2. Stop all running Services before shutting down the OS ";"Windows Server 2019";[CR][LF]

标签: powershellcarriage-returnlinefeed

解决方案


您可以-replace多次使用运算符来达到结果。

$original_file ='C:\Test\Server.csv'
$new_file = 'C:\Test\Server_changed.csv'

(Get-Content $original_file -Raw) -replace "(?<!\r)(\n)" -replace "\r(?!\n)","`r`n" |
    Set-Content $new_file -NoNewLine -Force

解释:

  • -replace是正则表达式替换运算符,而不是字符串类.Replace()-replace用于访问正则表达式机制负前瞻 ( (?!)) 和负后瞻 ( (?<!))。在每个-replace操作中,第一组引号代表正则表达式模式以捕获要替换的数据。第二组引号代表替换字符串。如果您未指定第二组引号,则将删除捕获的数据。

  • -Raw开关用于Get-Content防止 PowerShell 将文件作为数组读取,这将在内存中的数据中添加换行符。

  • -NoNewLineswitch onSet-Content用于不在输出文件末尾添加额外的尾随换行符。


推荐阅读