[英]How to do replace on multiple files with powershell
The aim is replace ",," with blank in the text files. 目的是在文本文件中用空白替换“,”。
The below works on single file: 以下适用于单个文件:
$path = "C:\Users\ThompsonHo\Desktop\testing\F181RMR CAN.txt"
$word = ",,"
$replacement = ""
$text = get-content $path
$newText = $text -replace $word,$replacement
$newText > $path
I try to make it handle for multiple files but fail, How to do replace on multiple files with powershell? 我尝试使其处理多个文件,但失败,如何用Powershell替换多个文件?
$path = "C:\Users\ThompsonHo\Desktop\testing\F18*.txt"
$word = ",,"
$replacement = ""
$text = get-content $path
$newText = $text -replace $word,$replacement
$newText > $path
You have to retrieve a list of files, then iterate over the list. 您必须检索文件列表,然后遍历该列表。
You can retrieve files that match a pattern with Get-ChildItem
(although Get-Item
would also work in this situation): 您可以使用Get-ChildItem
检索与模式匹配的文件(尽管在这种情况下, Get-Item
也可以使用):
$files = Get-ChildItem "C:\Users\ThompsonHo\Desktop\testing\F18*.txt"
That gives you an array of FileInfo
. 那给了你一个FileInfo
数组。 You can iterate over a collection with foreach
. 您可以使用foreach
遍历集合。
foreach ($file in $files) {
$file.FullName
}
$file.FullName
at this point will be the full path to the file. $file.FullName
此时将是文件的完整路径。
Your existing working solution for a single file should be easy to adapt. 您现有的单个文件工作解决方案应该易于调整。
$p="C:\temp"
$cs=Get-ChildItem -Path $p
foreach($c in $cs)
{
$t=Get-Content -Path $c.FullName -Raw
#$t -replace ",,",""|Out-File -FilePath $c.FullName -NoNewline
Set-Content -Path $c.FullName -Value ($t -replace ",,","") -NoNewline
}
尝试这个 :
Get-ChildItem "c:\temp\F18*.txt" | %{$file=$_.FullName; (Get-Content $file).Replace(',,', ',') | Out-File $file }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.