使用输出文件时避免换行
我对我正在编写的一个小 PowerShell 脚本感到有点沮丧。
基本上,我循环遍历文本文件,根据正则表达式模式数组检查每一行。 结果通过管道传输到输出文件 cmdlet,该 cmdlet 将其附加到另一个文本文件。
Get-ChildItem $logdir -Recurse -Include @('*.txt') | Get-Content | ForEach-Object {
Select-String $patterns -InputObject $_ | Out-File $csvpath -Append -Width 1000 }
我的问题是我无法让 out-file 省略它在 $csvpath 后面的文件中创建的那些附加换行符(每行后三个)。 我可以使用 .NET 框架类来实现相同的目标,但我宁愿坚持使用纯 PowerShell
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请记住,Select-String 输出 MatchInfo 对象而不是字符串 - 正如此命令所示:
您要求在输出到文件之前将 MatchInfo 对象隐式呈现为字符串。由于某种原因我不明白,这会导致输出额外的空行。您可以通过指定只希望将 Line 属性输出到文件来解决此问题,例如:
Keep in mind that Select-String outputs MatchInfo objects and not strings - as is shown by this command:
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.:
为什么不使用
Add-Content
?你不需要指定宽度和
-append
开关,默认情况下文件大小不会加倍(尽管你可以指定编码)而且看起来像你这样的空行没有问题有。Why don't you use
Add-Content
?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.