使用Regex/Powershell重命名文件

Dea*_*ean 22 regex powershell

我正在学习正则表达式,但我不知道如何将以下文件重命名为我想要的文件.你能帮助我吗.

顺便说一句,我发现使用Powershell重命名文件非常有用,它可以接受Regex.

filename__Accelerated_C ____ Practical_Programming_by_Example.chm - > C Example.chm实用编程

filename__Python_Essential_Reference__2nd_Edition_.pdf - > Python Essential Reference 2nd Edition.pdf

filename__Text_Processing_in_Python.chm - > Python.chm中的文本处理

我还包括一些我最喜欢使用的免费在线Regex工具,可能对其他人有用.

http://gskinner.com/RegExr/

http://www.rubular.com/

和cheatsheet

http://krijnhoetmer.nl/stuff/regex/cheat-sheet/

ste*_*tej 34

试试这个:

Get-ChildItem directory `
        | Rename-Item -NewName { $_.Name -replace '^filename_+','' -replace '_+',' ' }
Run Code Online (Sandbox Code Playgroud)

请注意,我只是将对象传递给Rename-Item它,实际上并不需要通过它来实现Foreach-Object(别名是%).

更新

我没有任何关于scriptblocks的'魔术'的记录.如果我没记错的话,如果属性是ValueFromPipelineByPropertyName=$true:

function x{
    param(
        [Parameter(ValueFromPipeline=$true)]$o,
        [Parameter(ValueFromPipelineByPropertyName=$true)][string]$prefix)
    process {
        write-host $prefix $o
    }
}
gci d:\ | select -fir 10 | x -prefix { $_.LastWriteTime }
Run Code Online (Sandbox Code Playgroud)


zda*_*dan 22

这应该工作:

ls | %{ ren $_ $(($_.name -replace '^filename_+','') -replace '_+',' ') }
Run Code Online (Sandbox Code Playgroud)

  • 为什么在第二个参数中使用`$`.我发现这也有效:`ls | %{ren $ _(($ _ -replace'filename_ +','') - replace'_ +','')}` (2认同)