Powershell相当于moreutils中的海绵? [英] Powershell equivalent to sponge in moreutils?

查看:45
本文介绍了Powershell相当于moreutils中的海绵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个名为 sponge 的 GNU 程序,它在写入文件之前吸收输入,因此您可以执行以下操作: cat myFile |grep "myFilter" |海绵我的文件

There's a GNU program called sponge that soaks up input before writing to a file so you can do something like this: cat myFile | grep "myFilter" | sponge myFile

是否有等效的 powershell,以便我可以就地处理文件,而无需通过管道传输到临时文件?

Is there a powershell equivalent, so I can work on a file in place, without having to pipe to a temporary file?

谢谢

推荐答案

在 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

这篇关于Powershell相当于moreutils中的海绵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆