2010-11-23 128 views
2

默认情况下,当您使用set-content Set-Content C:\test.txt "test","test1"时,提供的两个字符串之间用换行符分隔,但文件末尾还有一个换行符。powershell get-content忽略换行

如何在使用Get-Content时忽略带空格的换行符或换行符?

回答

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加入字符串,然后将其传递给方法。

注意:由于字符串连接效率不高,因此不推荐将它用于大文件。

+0

[`WriteAllLines`](http://msdn.microsoft.com/en-us/library/system.io.file.writealllines.aspx)方法工作使用集合,避免了将数组“`加入”到单个字符串中的需要:`[IO.File] :: WriteAllLines('c:\ test.txt',(“test”,'','Test1“)) ` – 2011-07-03 14:53:32

0

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

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

,或者使用多simplier [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 

$内容变量包含两个项目:“测试“,”test1“

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