powershell - 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]
解决方案
您可以-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 将文件作为数组读取,这将在内存中的数据中添加换行符。-NoNewLine
switch onSet-Content
用于不在输出文件末尾添加额外的尾随换行符。
推荐阅读
- opencv - 长焦镜头对大图像的相机标定误差较大
- laravel-5 - 模型创建后数据未真实保存在数据库中
- python - 我的 app.py 无法在后端接收请求并收到 404 错误
- javascript - 使用 react-apollo 进行服务器端渲染
- gradle - Beam 管道在直接运行器上运行正常时未在 Google Dataflow 中移动
- mysql - SQL 年龄组和唯一编号
- reactjs - 添加钩子组件时,比上一次渲染时渲染的钩子更多
- python - 使用鼠标仅在 pyqtgraph 中放大 x 或 y 方向
- bluetooth-lowenergy - 在 Ble5 中使用 Coded PHY 发送广告时,控制器如何知道应该使用 s=2 还是 s=8?
- asp.net-mvc - 如何调试 System.Web.dll?