简体   繁体   English

PS如何在文件名中间加符号

[英]How to add a symbol in a middle of a file name in PS

I have modified several thousand files with a various things requested by the owners.我已经根据所有者的要求修改了数千个文件。 Now, I need to add one final thing and I am not 100% on how to do it.现在,我需要添加最后一件事,但我不是 100% 知道如何去做。

Scenario is as follows - all files have a 10 digit number at the start, I need to add a hyphen after the number.场景如下 - 所有文件的开头都有一个 10 位数字,我需要在数字后添加一个连字符。 String is a variable but it is always the same length.字符串是一个变量,但它的长度始终相同。 1234567890abcdefgh.xls would be an example 1234567890abcdefgh.xls 就是一个例子

I have used GCI to make changes to symbols and static parts but not sure how to call for insertion in a specific place of a file (after the 10th character of a variable string)我已经使用 GCI 对符号和 static 部分进行了更改,但不确定如何调用插入文件的特定位置(在变量字符串的第 10 个字符之后)

Any ideas would be most welcome!任何想法都将受到欢迎!

You can use the $matches you get from the capturing groups of a -match comparison:您可以使用从-match比较的捕获组中获得的$matches

(Get-ChildItem -Path 'X:\WhereTheFilesAre' -File) | 
Where-Object { $_.BaseName -match '^(\d{10})([^-].*)' } |
Rename-Item -NewName { '{0}-{1}{2}' -f $matches[1], $matches[2], $_.Extension }

or by using the Substring() method:或者使用Substring()方法:

(Get-ChildItem -Path 'X:\WhereTheFilesAre' -File) | 
Where-Object { $_.BaseName -match '^\d{10}[^-]' } |
Rename-Item -NewName { $_.Name.Substring(0,10) + '-' + $_.Name.Substring(10) }

or use the regex -replace operator:或使用 regex -replace运算符:

(Get-ChildItem -Path 'X:\WhereTheFilesAre' -File) | 
Where-Object { $_.BaseName -match '^\d{10}[^-]' } |
Rename-Item -NewName { $_.Name -replace '^(\d{10})', '$1-' }

You can use string.Insert() to insert a string into another at a specific offset:您可以使用string.Insert()将一个字符串插入另一个字符串中的特定偏移量:

PS ~> '1234567890abcdefgh.xls'.Insert(10, '-')
1234567890-abcdefgh.xls

To apply to all files in a directory, you could do something like this:要应用于目录中的所有文件,您可以执行以下操作:

Get-ChildItem -File |Where-Object Name -match '^\d{10}[^-]' |Rename-Item -NewName { $_.Name.Insert(10, '-') }

The regular expression pattern ^\d{10}[^-] will only match file names that start with 10 digits followed by something other than a hyphen (to avoid renaming files that already comply with the naming convention)正则表达式模式^\d{10}[^-]将只匹配以 10 位数字开头后跟连字符以外的内容的文件名(以避免重命名已经符合命名约定的文件)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM