Search code examples
powershellfile-renamebatch-rename

Replace only first occurence of a character in filenames


I have a folder with many files. What I want is to replace the first matching character of each file. For example I have

aabbc.txt
aaabbxx.txt
aacbbbv.txt

I want to replace the first "b" with a "z" the result will be

aazbc.txt
aaazbxx.txt
aaczbbv.txt

so only the first match will be replaced what I tried is

Dir | Rename-Item -NewName { $_.name -replace "b","a" }

but it replace all the "b" in the filename.


Solution

  • Something like this should work:

    Dir | Rename-Item -NewName { $_.name -replace '^(.*?)b', '$1z' }
    

    The trick is to include the shortest match up to the first b ((.*?)) in the matching pattern and preserve it in the replacement by replacing it with itself ($1).