使用输出文件时避免换行

发布于 2024-08-29 12:31:22 字数 423 浏览 9 评论 0原文

我对我正在编写的一个小 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

椵侞 2024-09-05 12:31:22

请记住,Select-String 输出 MatchInfo 对象而不是字符串 - 正如此命令所示:

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

您要求在输出到文件之前将 MatchInfo 对象隐式呈现为字符串。由于某种原因我不明白,这会导致输出额外的空行。您可以通过指定只希望将 Line 属性输出到文件来解决此问题,例如:

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

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
青朷 2024-09-05 12:31:22

为什么不使用Add-Content

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

你不需要指定宽度和 -append 开关,默认情况下文件大小不会加倍(尽管你可以指定编码)而且看起来像你这样的空行没有问题有。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文