Avoid line breaks when using out-file

回眸只為那壹抹淺笑 提交于 2019-12-03 23:32:08

问题


I'm getting a little frustrated on a little PowerShell script I'm writing.

Basically I loop through text files to check every line against an array of regular expression patterns. The result gets piped to the out-file cmdlet which appends it to another text file.

Get-ChildItem $logdir -Recurse -Include @('*.txt') | Get-Content | ForEach-Object { 
Select-String $patterns -InputObject $_ | Out-File $csvpath -Append -Width 1000 }

My problem is that I can't get out-file to omit those additional line breaks it creates in the file behind $csvpath (three after each line). I could use .NET framework classes to achieve the same thing but I'd rather stick to pure PowerShell ;-)

Any help is greatly appreciated.

Kevin


回答1:


Why don't you use Add-Content?

gci $logdir -rec *.txt | gc | select-string $pattern | add-content $csvpath

You don't need to specify the width and -append switch, the file size is not doubled by default (although you can specify encoding) and it seems that there is no problem with the empty lines like you have.




回答2:


Keep in mind that Select-String outputs MatchInfo objects and not strings - as is shown by this command:

gci $logdir -r *.txt | gc | select-string $patterns | format-list *

You are asking for an implicit rendering of the MatchInfo object to string before being output to file. For some reason I don't understand, this is causing additional blank lines to be output. You can fix this by specifying that you only want the Line property output to the file e.g.:

gci $logdir -r *.txt | gc | select-string $patterns | %{$_.Line} | 
    Out-File $csvpath -append -width 1000


来源:https://stackoverflow.com/questions/2675552/avoid-line-breaks-when-using-out-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!