如何替换目录中每个文件的内容? [英] How to replace the content of every file in the directory?

查看:76
本文介绍了如何替换目录中每个文件的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个函数 (Function($_)) 可以将目录中的每个文件的所有1"替换为2".新内容写入文件 out.txt.

There is a function (Function($_)) that replace all "1" with "2" for each file in the directory. New content is written to the file out.txt.

输入:in.txt →111

input: in.txt → 111

输出:in.txt →第222话输出.txt

output: in.txt → 222 → out.txt

请告诉我,如何在每个文件中进行替换?

Tell me, please, how to make the replacement take place inside of every file?

Get-Content "C:\Dir\*" | ForEach-Object {Function($_)} > C:\Dir\out.txt

推荐答案

Get-Content "C:\Dir\*" 会给你 C:\Dir 中所有内容的内容 一次性完成,因此您将无法单独修改每个文件.C:\Dir 中的任何目录也会出错.

Get-Content "C:\Dir\*" will give you the content of everything in C:\Dir in one go, so you won't be able to modify each file individually. You'll also get errors for any directory in C:\Dir.

您需要遍历目录中的每个文件并单独处理它们:

You need to iterate over each file in the directory and process them individually:

Get-ChildItem 'C:\Dir' -File | ForEach-Object {
  $file = $_.FullName
  (Get-Content $file) -replace '1','2' | Set-Content $file
}

Get-Content 周围的括号确保在进一步处理之前读取并再次关闭文件,否则写入(仍然打开)文件将失败.

The parentheses around Get-Content ensure that the file is read and closed again before further processing, otherwise writing to the (still open) file would fail.

请注意,参数 -File 仅在 PowerShell v3 或更高版本中受支持.在旧版本中,您需要将 Get-ChildItem -File 替换为以下内容:

Note that the parameter -File is only supported in PowerShell v3 or newer. On older versions you need to replace Get-ChildItem -File with something like this:

Get-ChildItem 'C:\Dir' | Where-Object { -not $_.PSIsContainer } | ...

这篇关于如何替换目录中每个文件的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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