我有50个文件,文件名的格式如下:
Auth
我想将其更改为:
Basic Authentication
我想更新文件名的一部分并添加下划线,而不是名称中的第一个空格。
谢谢
我试图在Powershell中编写脚本
SIGMOID 01012019 - 01082019.XLS
SIGMOID 01012019 - 01022019.XLS
但是会更新每个空白。
答案 0 :(得分:0)
也许不是最优雅的解决方案,但也许正是您想要的:
Rename-Item -NewName { $_.name -replace "SIGMOID ","SIGMOID_" }
答案 1 :(得分:0)
假设您有以下文件:
SIGMOID 01012019 - 01082019.XLS SIGMOID 01012019 - 01022019.XLS SOMETHINGELSE 01012019 - 02022019.XLS YETANOTHERPREFIX 01012019 - 03022019.XLS
然后以下代码将其重命名:
$sourceFolder = 'THE PATH OF THE ROOTFOLDER THAT STORES THE XLS FILES TO RENAME' #'# enter your rootpath here
Get-ChildItem -Path $sourceFolder -File |
Where-Object { $_.Name -match '^\w+ +\d{8}.*\.xlsx?' } |
ForEach-Object {
$_ | Rename-Item -NewName ($_.Name -replace '^(\w+) +(\d{8}.*\.xlsx?)', '$1_$2') -WhatIf
}
成为
SIGMOID_01012019 - 01082019.XLS SIGMOID_01012019 - 01022019.XLS SOMETHINGELSE_02012019 - 01022019.XLS YETANOTHERPREFIX_03012019 - 01022019.XLS
注意:如果您对结果感到满意,请删除-WhatIf
正则表达式详细信息:
^ Assert position at the beginning of a line (at beginning of the string or after a line break character)
( Match the regular expression below and capture its match into backreference number 1
\w Match a single character that is a “word character” (letters, digits, etc.)
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
\ Match the character “ ” literally
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
( Match the regular expression below and capture its match into backreference number 2
\d Match a single digit 0..9
{8} Exactly 8 times
. Match any single character that is not a line break character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\. Match the character “.” literally
xls Match the characters “xls” literally
x Match the character “x” literally
? Between zero and one times, as many times as possible, giving back as needed (greedy)
)
答案 2 :(得分:0)
将我的评论变成答案
仅在第一个空格处拆分名称,并在下划线处加入
'* *'
确保文件名中至少有一个空格。
Get-ChildItem '* *' |
Rename-Item -NewName {($_.Name -split ' ',2 -join '_')} -Whatif
如果输出看起来正常,请删除-WhatIf
在连续运行中,这会将示例中的-
更改为_-
等。
为避免出现这种情况,您需要使用Where-Object
来排除带下划线的文件。
Get-ChildItem '* *' |
Where-Object Name -notmatch '^\S+_' |
Rename-Item -NewName {($_.Name -split ' ',2 -join '_')} -Whatif
答案 3 :(得分:0)
嗯,如何更换两次:
'SIGMOID 01012019 - 01082019.XLS' -replace ' ','_' -replace '_-_',' - '
SIGMOID_01012019 - 01082019.XLS
或(替换两边没有破折号的空间):
'SIGMOID 01012019 - 01082019.XLS' -replace '[^-] [^-]','_'
SIGMOI_1012019 - 01082019.XLS
尝试使用重命名项-whatif ...