View Single Post
Old 12-17-2007   #5 (permalink)
Shay Levi
Guest


 
 

Re: How to work with regular expressions


## create test files

1..9 | foreach {new-item -path ".\powershell_0$_.txt" -itemtype file -force}

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 17/12/2007 21:22:03 0.0 B powershell_01.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_02.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_03.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_04.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_05.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_06.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_07.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_08.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_09.txt



## get all files and rename
dir powershell_*.* | foreach {
[int]$num = ([regex]'\d+').match($_.name).value
rename-item $_.name "powershell_$num.txt" -force
}


dir powershell_*.*

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 17/12/2007 21:22:03 0.0 B powershell_1.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_2.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_3.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_4.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_5.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_6.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_7.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_8.txt
-a--- 17/12/2007 21:22:03 0.0 B powershell_9.txt



-----
Shay Levi
$cript Fanatic
http://scriptolog.blogspot.com
Hebrew weblog: http://blogs.microsoft.co.il/blogs/scriptfanatic


Quote:

> Hi!
>
> When I do:
>
> dir | where { $_.Name -match "\d+" }
>
> It displays names containing numbers. What if I want to have just
> those matched numbers?
>
> So if the file name is : powerShell_01.txt
> I want to have this 01 how to get this?
> Later on I'd like to convert it to a number so if it's 0001 or 001 or
> 000001 it's just 1.
>
> and rename files
>
> Thx for help with this.
>
> Jedrzej
>

My System SpecsSystem Spec