Reputation: 41
I need to replace multiple strings in multiple filenames. Here's something representative of what my data looks like.
CAL aB12 AUG.docx CAL cDe345 AUG.docx CAL FGHiJKL6789 AUG.docx
I need to replace "CAL" with "Calendar" and "AUG" with "August" in the filenames.
The best I've been able to do is run two cmdlets (one for each replacement) chained together with a semicolon. This works, but I know it's crude.
gci | Rename-Item -NewName { $_ -replace "CAL", "Calendar" };
gci | Rename-Item -NewName { $_ -replace "AUG", "August" }
After extensive searching, I found StackOverflow 3403217. Due to a lack of knowledge and experience I haven't been able (and I've tried hard) to translate any of the five answers it provides into a single cmdlet that works for what it is that I'm trying to do.
p.s. I paste copies of the files of interest into C:\Temp and work from there. I'm using Windows 7.
Upvotes: 3
Views: 1441
Reputation: 200523
All you need to do is daisy-chain the replacement operations:
gci | Rename-Item -NewName { $_.Name -replace "CAL","Calendar" -replace "AUG","August" }
As @Esperento57 mentioned in the comments the -replace
operator does regular expression replacements. In your case it doesn't make a difference, but if your search strings contain special characters they may require escaping, e.g.:
gci | Rename-Item -NewName { $_.Name -replace [regex]::Escape("CAL"),"Calendar" -replace [regex]::Escape("AUG"),"August" }
Or you could do simple string replacements by daisy-chaining Replace()
method calls:
gci | Rename-Item -NewName { $_.Name.Replace("CAL","Calendar").Replace("AUG","August") }
Upvotes: 1
Reputation: 17492
try Something like this
$hashreplace = @{}
$hashreplace.'old1' = 'new1'
$hashreplace.'old2' = 'new2'
Get-ChildItem -Recurse -File -Path "c:\temp\" | % {
$filename = $_.FullName
$text = $_.Name
$hashreplace.Keys | %{if ($text -ne $null) {$text = $text.Replace($_, $hashreplace[$_]) } }
Rename-Item -Path $filename -NewName $text
}
Upvotes: 1
Reputation: 69
Get-Content List.txt |
Where-Object \\{ $_ -match '^\\\\' \\} |
ForEach-Object \\{ $_ -replace
'^\\\\(\S+).+','$1' \\}
You basically need to grab the text file and find matches for whatever String you want and run through a for loop in order to replace it. Why do it in Powershell? I don't know.
Upvotes: -1