当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 在 PowerShell 中替换多个文件中的字符串 [2 种方法]

作者:精品下载站 日期:2024-12-14 05:23:23 浏览:14 分类:玩电脑

在 PowerShell 中替换多个文件中的字符串 [2 种方法]


? TL;DR 要替换多个文件中的字符串,请使用 Get-ChildItem 获取所有必需的文件并使用 迭代文件ForEach-Object。在每次迭代中,使用 Get-Content cmdlet 读取文件内容,使用 replace() 方法替换文本,并使用 Set-Content 保存文件中的内容。
这是一个简单的示例:

假设您想要将文件夹 C:\Users\Arpit\Desktop\powershell 下的所有 txt 文件中的所有空格替换为下划线。

在 PowerShell 中替换多个文件中的文本:

$DirPath = "C:\Users\Arpit\Desktop\powershell"
 get-childitem $DirPath -recurse -include *.txt |
ForEach-Object {
 (Get-Content $_).replace(" ","_") |
 Set-Content $_
 }

在 PowerShell 中替换多个文件中的字符串

有 2 种不同的方法可以在 PowerShell 中替换多个文件中的字符串。

将 Replace() 方法与 Get-ChildItem 一起使用

以下是使用 replace() 方法替换多个文件中的字符串的步骤。

  • 将文件路径存储在变量 $DirPath
  • 使用 Get-ChildItem cmdlet 获取 $DirPath 中的所有必需文件。您可以使用 -include 选项仅选择特定的文件扩展名。
  • 使用 ForEach-Object 迭代每个项目。
  • 在每次迭代中,使用 Get-Content cmdlet 读取文件的内容。 Get-Content 读取路径指定的特定位置处的项目内容。
  • 使用 replace() 方法用新文本替换旧文本。 replace() 方法返回新字符串并用新文本替换每次出现的旧文本。
  • 最后,使用Set-Content cmdlet 替换所有文件的内容。

使用replace方法替换PowerShell中多个文件中的文本:

$DirPath = "C:\Users\Arpit\Desktop\powershell"
 get-childitem $DirPath -recurse -include *.txt |
ForEach-Object {
 (Get-Content $_).replace(" ","_") |
 Set-Content $_
 }

将替换运算符与 Get-ChildItem 一起使用

大多数步骤与之前的方法类似。我们将使用替换运算符代替 replace() 方法来替换多个文件中的内容。

以下是使用 replace 运算符替换多个文件中的字符串的步骤。

  • 将文件路径存储在变量 $DirPath
  • 使用 Get-ChildItem cmdlet 获取 $DirPath 中的所有必需文件。您可以使用 -include 选项仅选择特定的文件扩展名。
  • 使用 ForEach-Object 迭代每个项目。
  • 在每次迭代中,使用 Get-Content cmdlet 读取文件的内容。 Get-Content 读取路径指定的特定位置处的项目内容。
  • 使用replace运算符将旧文本替换为新文本。 replace 运算符返回新字符串,并用新文本替换每次出现的旧文本。
  • 最后,使用Set-Content cmdlet 替换所有文件的内容。

使用replace方法替换PowerShell中多个文件中的文本:

$DirPath = "C:\Users\Arpit\Desktop\powershell"
 get-childitem $DirPath -recurse -include *.txt |
ForEach-Object {
 (Get-Content $_) -replace " ","_" |
 Set-Content $_
 }

这就是如何在 PowerShell 中替换多个文件中的字符串。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯