'How to add a symbol in a middle of a file name in PS
I have modified several thousand files with a various things requested by the owners. Now, I need to add one final thing and I am not 100% on how to do it.
Scenario is as follows - all files have a 10 digit number at the start, I need to add a hyphen after the number. String is a variable but it is always the same length. 1234567890abcdefgh.xls would be an example
I have used GCI to make changes to symbols and static parts but not sure how to call for insertion in a specific place of a file (after the 10th character of a variable string)
Any ideas would be most welcome!
Solution 1:[1]
You can use string.Insert()
to insert a string into another at a specific offset:
PS ~> '1234567890abcdefgh.xls'.Insert(10, '-')
1234567890-abcdefgh.xls
To apply to all files in a directory, you could do something like this:
Get-ChildItem -File |Where-Object Name -match '^\d{10}[^-]' |Rename-Item -NewName { $_.Name.Insert(10, '-') }
The regular expression pattern ^\d{10}[^-]
will only match file names that start with 10 digits followed by something other than a hyphen (to avoid renaming files that already comply with the naming convention)
Solution 2:[2]
You can use the $matches
you get from the capturing groups of a -match
comparison:
(Get-ChildItem -Path 'X:\WhereTheFilesAre' -File) |
Where-Object { $_.BaseName -match '^(\d{10})([^-].*)' } |
Rename-Item -NewName { '{0}-{1}{2}' -f $matches[1], $matches[2], $_.Extension }
or by using the Substring()
method:
(Get-ChildItem -Path 'X:\WhereTheFilesAre' -File) |
Where-Object { $_.BaseName -match '^\d{10}[^-]' } |
Rename-Item -NewName { $_.Name.Substring(0,10) + '-' + $_.Name.Substring(10) }
or use the regex -replace
operator:
(Get-ChildItem -Path 'X:\WhereTheFilesAre' -File) |
Where-Object { $_.BaseName -match '^\d{10}[^-]' } |
Rename-Item -NewName { $_.Name -replace '^(\d{10})', '$1-' }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mathias R. Jessen |
Solution 2 |