如何使用 PowerShell 替换换行符?

问题描述 投票:0回答:6

给定 test.txt 包含:

test
message

我想结束:

testing
a message

我认为以下应该有效,但事实并非如此:

Get-Content test.txt |% {$_-replace "t`r`n", "ting`r`na "}

如何查找并替换我找到的包含 CRLF 的位置?

powershell
6个回答
52
投票

CRLF 是两个字符,当然是 CR 和 LF。然而,

`n
由两者组成。例如:

PS C:\> $x = "Hello
>> World"

PS C:\> $x
Hello
World
PS C:\> $x.contains("`n")
True
PS C:\> $x.contains("`r")
False
PS C:\> $x.replace("o`nW","o There`nThe W")
Hello There
The World
PS C:\>

我认为您遇到了

`r
的问题。我能够从您的示例中删除
`r
,仅使用
`n
,并且它有效。当然,我不知道你到底是如何生成原始字符串的,所以我不知道里面有什么。


32
投票

根据我的理解,Get-Content在通过管道滚动文本文件时消除了所有换行符/回车符。要执行多行正则表达式,您必须将字符串数组重新组合成一个巨大的字符串。我做类似的事情:

$text = [string]::Join("`n", (Get-Content test.txt))
[regex]::Replace($text, "t`n", "ting`na ", "Singleline")

澄清:小文件仅限各位!请不要在您的 40 GB 日志文件上尝试此操作:)


28
投票

使用

-Raw
Get-Content
参数进行多行匹配。

默认情况下,Get-Content 从文件中返回行数组。

示例(来自 PowerShell 7)显示仅添加

-Raw
参数会返回您所期望的结果:

Get-Content test.txt -Raw |% {$_-replace "t`r`n", "ting`r`na "}
testing
a message

引用自 Get-Help 的解释:

❯ Get-Help Get-Content -Parameter Raw

-Raw <System.Management.Automation.SwitchParameter>
    Ignores newline characters and returns the entire contents of a file in one string with the newlines
    preserved. By default, newline characters in a file are used as delimiters to separate the input into an
    array of strings. This parameter was introduced in PowerShell 3.0. Raw is a dynamic parameter that the
    FileSystem provider adds to the `Get-Content` cmdlet This parameter works only in file system drives.

7
投票

如果您想删除所有换行符并将其替换为某些字符(例如逗号),则可以使用以下命令。

(Get-Content test.txt) -join ","

这是有效的,因为 Get-Content 返回行数组。您可以将其视为多种语言中可用的 tokenize 函数。


1
投票

您也可以将

"\\r\\n"
用于
powershell
中的新行。我已经在 servicenow 工具中使用了这个。

在我的情况下

"\r\n"
不起作用,所以我尝试
"\\r\\n"
作为
"\"
这个符号在
powershell
中用作转义字符。


0
投票

您可以使用这个简单的 Powershell 指令检测文件是否为 CRLF

(cat -Raw $args) -match "\r\n$"

更换 和 这很棘手,因为您必须首先检测它并仅在需要时才应用替换,否则会很混乱。太复杂了。

在任何情况下,您都可以忘记检测,以确保文件是 CRLF,无论原始类型如何,您都可以在 PowerShell 中执行此操作:

cat $file > $file
© www.soinside.com 2019 - 2024. All rights reserved.