2

When you use set-content Set-Content C:\test.txt "test","test1" by default the two provided strings are separated by a newline, but there is also a newline at the end of the file.

How do you ignore this newline or newline with spaces when using Get-Content?

foureight84
  • 402
  • 2
  • 7
  • 19

3 Answers3

1

You can remove empty line like this:

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

However, it will remove the string in the middle as well.
Edit: Actually as I tried the example, I noticed that Get-Content ignores the last empty line added by Set-Content.

I think your problem is in Set-Content. If you use workaround with WriteAllText, it will work fine:

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

You pass a string as second parameter. That's why I first joined the strings via -join and then passed it to the method.

Note: this is not recommended for large files, because of the string concatenation that is not efficient.

stej
  • 28,745
  • 11
  • 71
  • 104
  • The [`WriteAllLines`](http://msdn.microsoft.com/en-us/library/system.io.file.writealllines.aspx) method works with collections, avoiding the need to `-join` the array into a single string: `[IO.File]::WriteAllLines('c:\test.txt', ("test",'',"Test1"))` – Emperor XLII Jul 03 '11 at 14:53
0

it is default behavior that Set-Content adds new line because it lets you set-content with arrays of strings and get them one per line. Anyway Get-Content ignores last "new line" (if there are no spaces behind). work around for Set-Content:

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

or use much simplier [io.file]::WriteAllText

can you specify exact situation (or code)?

for example if you want to ignore last line when getting content it would look like:

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

but if you just do:

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

$content variable contains two items: "test","test1"

henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
Tomas Panik
  • 4,337
  • 2
  • 22
  • 31
0
Get-Content C:\test.txt | Where-Object {$_ -match '\S'}
Shay Levy
  • 121,444
  • 32
  • 184
  • 206