powershell get-content忽略换行符

时间:2010-11-23 06:41:17

标签: regex powershell get newline

默认使用set-content Set-Content C:\test.txt "test","test1"时,两个提供的字符串由换行符分隔,但文件末尾也有换行符。

使用Get-Content时,如何忽略这个带换行符的换行符或换行符?

3 个答案:

答案 0 :(得分:1)

你可以删除这样的空行:

Set-Content C:\test.txt "test",'',"test1"
Get-Content c:\test.txt | ? { $_ }

但是,它也会删除中间的字符串。
编辑:实际上,当我尝试使用该示例时,我注意到Get-Content忽略了由Set-Content添加的最后一个空行。

我认为您的问题出在Set-Content。如果您对WriteAllText使用变通方法,它将正常工作:

[io.file]::WriteAllText('c:\test.txt', ("test",'',"test1" -join "`n"))

您传递一个字符串作为第二个参数。这就是我首先通过-join加入字符串然后将其传递给方法的原因。

注意:这不建议用于大型文件,因为字符串连接效率不高。

答案 1 :(得分:0)

Set-Content添加新行是默认行为,因为它允许您使用字符串数组设置内容并每行获取一行。无论如何Get-Content忽略了最后的“新行”(如果后面没有空格)。 解决Set-Content:

([byte[]][char[]] "test"), ([byte]13), ([byte]10) ,([byte[]][char[]] "test1") | 
   Set-Content c:\test.txt -Encoding Byte

或使用更简单的[io.file]::WriteAllText

你能指定确切的情况(或代码)吗?

例如,如果要在获取内容时忽略最后一行,它将如下所示:

$content = Get-Content c:\test.txt
$length = ($content | measure).Count
$content = $content | Select-Object -first ($length - 1)

但如果您这样做:

"test","test1" | Set-Content C:\test.txt 
$content = Get-Content C:\test.txt 

$content变量包含两个项目:"test","test1"

答案 2 :(得分:0)

Get-Content C:\test.txt | Where-Object {$_ -match '\S'}