2010-11-23 179 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'}