Reputation: 35
I got some help with this question
Renaming a range from files w/Powershell - from first to third from last hyphen
and it worked wonderfully, but now I have a new problem.
My csv file names now have random numbers of hyphens like so:
abc-def-ghi-jkl-mno-pqr-s-tuv-ke-traffic-by-domains-17-Oct-2018_23-49-38-6d73395f476ad09a7506dc00533933b8.csv
abc-def-ghi-jkl-ke-traffic-by-domains-15-Oct-2018_05-20-36-75eabae7c4123198ff5fe6f4f642449f.csv
abc-def-ghi-jkl-mno--ke-traffic-by-domains-12-Oct-2018_06-23-58-b13eb8f362c09fbe405458fac8af8f8e.csv
The number of hyphens change from file to file.
I would like to rename them with powershell to
abc-17-Oct-2018.csv
abc-15-Oct-2018.csv
abc-12-Oct-2018.csv
I tried the following:
1.Delete everything after "_"
Get-ChildItem -Filter *.csv | Foreach-Object -Process {
$NewName = [Regex]::Match($_.Name,"^[^_]*").Value + '.csv'
$_ | Rename-Item -NewName $NewName
}
2.Delete everything after the first "-" until "ke-traffic-by-domains-"
Get-ChildItem -Filter *.csv | Rename-Item -NewName {
$word = "-*ke-traffic-by-domains-"
$NewName = $_.Name -split $word + '.csv'
$_ | Rename-Item -NewName $NewName
}
But I'm stuck on No.2 deleting a range with regular expression.
Can someone kindly show me a way to change the file names?
Upvotes: 0
Views: 95
Reputation:
Use a regular expression to match your criteria (see Regex101.com)
Get-ChildItem *.csv |
Where-Object Name -match '^([^\-]+)-.*?-traffic-by-domains-(\d{1,2}-\D{3}-20\d{2})_'|
Rename-Item -NewName {"{0}-{1}.csv" -f $Matches[1],$Matches[2]} -WhatIf
If the output looks OK, remove the trailing -WhatIf
Files on my Ramdrive after running the script over your sample csv names:
> gci
Verzeichnis: A:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2018-11-05 09:38 0 abc-12-Oct-2018.csv
-a---- 2018-11-05 09:38 0 abc-15-Oct-2018.csv
-a---- 2018-11-05 09:38 0 abc-17-Oct-2018.csv
Upvotes: 2