I have some zip files that all ends with:
Some nameA 1.0.0 rev. 110706.zip
Some nameB 1.0.0 rev. 110806.zip
Some name moreC 1.0 rev. 120904.zip
name 1.1 rev. 130804.zip
In PowerShell I would like to read those file names, create a new text file that contains only the versions but converted into the following format:
1.0.0.110706
1.0.0.110806
1.0.120904
1.1.130804
For now I do:
$files = Get-ChildItem "." -Filter *.zip
for ($i=0; $i -lt $files.Count; $i++) {
$FileName = $files[$i].Name
$strReplace = [regex]::replace($FileName, " rev. ", ".")
$start = $strReplace.LastIndexOf(" ")
$end = $strReplace.LastIndexOf(".")
$length = $end-$start
$temp = $strReplace.Substring($start+1,$length-1)
$temp
}
I have looked at: Use Powershell to replace subsection of regex result
To see if I can get a more compact version of this. Any suggestions given the above pattern?
You could do a single -replace operation:
$FileName -replace '^\D+([\.\d]+)\srev\.\s(\d+)','$1.$2'
Breakdown:
^\D+ # 1 or more non-digits - matches ie. "Some nameA "
([\.\d]+) # 1 or more dots or digits, capture group - matches the version
\srev\.\s # 1 whitespace, the characters r, e and v, a dot and another whitespace
(\d+) # 1 or more digits, capture group - matches the revision number
In the second argument, we refer to the two capture groups with $1 and $2
You can pipe Get-ChildItem to ForEach-Object instead of using a for loop and indexing into $files:
Get-ChildItem . *.zip |ForEach-Object {
$_.BaseName -replace '^\D+([\.\d]+)\srev\.\s(\d+)','$1.$2'
} | Out-File output.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With