且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Powershell相当于moreutils中的海绵?

更新时间:2021-09-12 05:09:33

在 Powershell 中,明智地使用括号将强制操作在将数据传递给管道中的下一个命令之前完全完成.管道 Get-Content 的默认管道是逐行管道到下一个命令,但在继续之前,它必须使用括号形成一个完整的数据集(例如,加载所有行):

In Powershell, judicious use of parentheses will force an operation to completely finish before passing data to the next command in the pipeline. The default for piping Get-Content is to pipe line by line to the next command, but with parentheses it must form a complete data set (e.g., load all lines) before continuing:

(Get-Content myFile) | Select-String 'MyFilter' | Set-Content myFile

另一种可能使用较少内存的替代方法(我没有对其进行基准测试)是仅强制 Select-String 的结果在继续之前完成:

An alternative that may use less memory (I have not benchmarked it) is to only force the results of Select-String to complete before continuing:

(Get-Content myFile | Select-String 'MyFilter') | Set-Content myFile

您还可以将事物分配给变量作为附加步骤.任何技术都会将内容加载到 Powershell 会话的内存中,所以要小心处理大文件.

You could also assign things to a variable as an additional step. Any technique will load the contents into the Powershell session's memory, so be careful with big files.

附录: Select-String 返回 MatchInfo 对象.使用 Out-File 会添加讨厌的额外空行,因为它试图将结果格式化为字符串,但 Set-Content 正确地将每个对象转换为自己的字符串它写入,产生更好的输出.由于您来自 *nix 并且习惯于返回字符串的所有内容(而 Powershell 返回对象),强制字符串输出的一种方法是通过转换它们的 foreach 管道:

Addendum: Select-String returns MatchInfo objects. Using Out-File adds pesky extra blank lines due to the way it tries to format the results as a string, but Set-Content correctly converts each object to its own string as it writes, producing better output. Being that you're coming from *nix and are used to everything returning strings (whereas Powershell returns objects), one way to force string output is to pipe them through a foreach that converts them:

(Get-Content myFile | Select-String 'MyFilter' | foreach { $_.tostring() }) | Set-Content myFile