Concatenate files using PowerShell

北战南征 提交于 2019-12-18 18:54:05

问题


I am using PowerShell 3.

What is best practice for concatenating files?

file1.txt + file2.txt = file3.txt

Does PowerShell provide a facility for performing this operation directly? Or do I need each file's contents be loaded into local variables?


回答1:


If all the files exist in the same directory and can be matched by a simple pattern, the following code will combine all files into one.

Get-Content .\File?.txt | Out-File .\Combined.txt



回答2:


I would go this route:

Get-Content file1.txt, file2.txt | Set-Content file3.txt

Use the -Encoding parameter on Set-Content if you need something other than ASCII which is the default for Set-Content.




回答3:


a generalization based on @Keith answer:

gc <some regex expression> | sc output




回答4:


If you need more flexibility, you could use something like

Get-ChildItem -Recurse *.cs | ForEach-Object { Get-Content $_ } | Out-File -Path .\all.txt


来源:https://stackoverflow.com/questions/16952138/concatenate-files-using-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!