views:

62

answers:

3

I am trying to rename multiple files in windows using powershell. And I want to rename replacing this pattern:

"123456-the_other_part_of_the_string". Example:

409873-doc1.txt
378234-doc2.txt
1230-doc3.txt

Basically I want to crop the numbers + '-' thing.

+2  A: 
$variable -replace "^\d+-", ""
NullUserException
Thank you what I was missing was the "+" thing was what I was missing.
Melladric
A: 
[0-9]*?-[^.]*

I'd recommend you take some time to learn regex, though, instead of just using answers from SO. You will run into all sorts of unusual file naming that may throw your program off in the real world and you woln't be able to fix these issues without understanding regex.

EDIT: Not sure if you also want to remove the 'name' part. If not, use this instead:

[0-9]*?-
Computerish
This will match stuff in the middle of the string like `file0921-f.txt`
NullUserException
Thank you very much for answering. Yeah, I've been wanting to learn some regex and I've been looking and gathering lots of sample codes, but it still didn't fix in my mind. This was kinda of a problem I've put to myself to see how much I have understood so far (not very much as you see), I tried lots of things, but the expressions I tried simply didn't work as expected, so I decided to see how it would be done...
Melladric
The way I learned regex was playing around with RegExr: http://gskinner.com/RegExr/ That and answering questions on SO. :-)Also, NullUserException is correct. This would be better: `\b[0-9][0-9]*?-[^.]*`
Computerish
A: 
Get-ChildItem . *.txt | Where {$_.Name -match '^\d+-(.*)'} | 
                        Rename-Item -NewName {$matches[1]}

or with aliases:

gci . *.txt | ?{$_.Name -match '^\d+-(.*)'} | rni -new {$matches[1]}
Keith Hill
Thanks for the answer, I was hoping to see some PS code it was very helpful!
Melladric