3

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?

0

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

4 Comments

hm cool but I still get the zip extension in result if I use the above, e.g. '1.0.0.150806.zip'
@u123 sorry, thought you were trying to rename the files, just updated the answer to output the versions to a file instead
You don't need to escape the . in [\.\d].
@KeithHill true, but it makes it more obvious what he's trying to do

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.