在PowerShell中如何替换回车 [英] In PowerShell how to replace carriage return
问题描述
在 PowerShell 脚本中,我将从 SQL Server 查询中读取的数据导出到以制表符分隔的 .csv 文件中.我需要删除所有回车符.
In a PowerShell script I'm exporting data read from a SQL Server query into a .csv file tab delimited. I need to remove any carriage return characters.
-replace '`r`n'
不起作用.我认为字符是 char(13)
.
-replace '`r`n'
isn't working. I think the character is char(13)
.
这是我不起作用的代码行:
Here's my code line that doesn't work:
(Get-Content $MyCSV_DOR) | % {$_ -replace '`r`n', " "} | out-file -FilePath $MyCSV_DOR -Force -Encoding ascii
我也尝试了以下方法:
`r, `n, \r, \n and \r\n
他们都无法删除字符.我还查看了建议的其他帖子.
All of them fail to remove the character. I've also looked at the suggested other posts.
有什么建议吗?
推荐答案
默认情况下,get-content
自动将文件拆分为换行符,如果 out-file
接收一组行,它将换行符放回原处.所以你的 -replace
什么都不做,因为换行符已经被 Get-Content
删除了.您需要使用 -raw
参数将文件作为单个文本块读取.以下应该做你想做的
By default, get-content
automatically splits a file into lines on newlines and if out-file
receives an array of lines, it puts the newlines back. So your -replace
does nothing because the newlines have already been removed by Get-Content
. You need to use the -raw
parameter to read the file as a single block of text. The following should do what you want
(Get-Content -Raw $MyCSV_DOR) -replace "[`r`n']+, ' ' |
Out-File -FilePath $MyCSV_DOR -Force -Encoding ascii -nonewline
注意:我更改了替换模式以用一个空格替换一个或多个回车或换行符的任何序列
Note: I changed the replace pattern to replace any sequence of one or more of carriage return or newline characters by a single space
这篇关于在PowerShell中如何替换回车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!