powershell - 在 PowerShell 上保存带有原始标头的已清理日志文件
问题描述
有必要从带有日志的文件中删除带有数据切片的行。我的解决方案如下所示:
Get-Content C:\Users\User\Desktop\Performance_.log |
Select-String -Pattern '(202007|202008|202009)' |
%{$_.ToString()} |
Out-File C:\Users\User\Desktop\out.log
但是文件保存时没有标题。请告诉我如何用标题重新保存文件。我无法在 PS 上实现它。我不懂语言。非常感谢!
解决方案
$header = Get-Content 'C:\Users\User\Desktop\Performance_.log' -First 1
$content = Get-Content C:\Users\User\Desktop\Performance_.log | Select-String -Pattern '(202007|202008|202009)' | % {$_.ToString()}
#Output to file
$header | Out-File C:\Users\User\Desktop\out.log
$content | Out-File C:\Users\User\Desktop\out.log -append
我两次获取内容,放入两个变量。然后我们使用 out-file 创建一个带有标题的文件,然后我们再次执行 out-file ,但这次-append
设置了标志,这样标题就不会被覆盖。
如果您使用的是 CSV,我不会使用上述方法。我会改为使用 import-csv。在我看来,csv 对象比字符串更容易处理,也更灵活。
$content = import-csv 'C:\Users\User\Desktop\Performance_.log' | where-object {$_.ExampleFirstColumn -match '(202007|202008|202009)'}
$content | Export-csv "C:\Users\User\Desktop\out.log" -NoTypeInformation
只需将上面代码中的“ExampleFirstColumn”文本替换为标题的名称即可。
推荐阅读
- javascript - Blurry Image on canvas
- python - 以特定模式结尾的字符串的正则表达式
- matlab - 如何在MATLAB的一个窗口中绘制多个图形
- java - 我该如何解决这个数组问题?汽车存放方案
- html - 在悬停时推动两侧
- python - Problem when trying to play mp3 file with QMediaPlayer PyQt5
- stored-procedures - Stored procedure to return output parameter with description of error encountered
- excel - Excel 无法读取日期和时间数据
- python - Python 程序运行时没有错误,但没有给出所需的输出
- azure-devops - 我可以在我的 Azure Devops 项目的 bitbucket 中获取我的源吗?