如何将文件名的一部分移动到不同的位置

Vit*_*ano 2 regex powershell file-rename batch-rename rename-item-cmdlet

我在一个文件夹中有一组文件。我想通过将文件名的一部分移动到不同位置来编辑所有文件名。这是我所拥有的样本:

Par1_MD_0_5_AL_2_ND_4_Dist_0_Pot_Drop_out.txt        
Par1_MD_0_5_AL_2_ND_4_Dist_1_Pot_Drop_out.txt        
Par1_MD_0_5_AL_2_ND_6_Dist_2_Pot_Drop_out.txt        
Par1_MD_0_5_AL_2_ND_8_Dist_3_Pot_Drop_out.txt  
Run Code Online (Sandbox Code Playgroud)

这就是我想要的:

Par1_MD_0_5_AL_2_Dist_0_ND_4_Pot_Drop_out.txt        
Par1_MD_0_5_AL_2_Dist_1_ND_4_Pot_Drop_out.txt        
Par1_MD_0_5_AL_2_Dist_2_ND_6_Pot_Drop_out.txt        
Par1_MD_0_5_AL_2_Dist_3_ND_8_Pot_Drop_out.txt
Run Code Online (Sandbox Code Playgroud)

基本上,我想在“Dist_(number)”之后放置“ND_(number)”

感谢您的帮助。

小智 5

你可以试试:

(.*?)(ND_\d_)(Dist_\d_)(.*)
Run Code Online (Sandbox Code Playgroud)

上述正则表达式的解释:

  • (.*?)- 表示第一个捕获组懒惰地匹配之前的所有内容ND
  • (ND_\d_)- 表示第二个捕获组匹配ND_后跟一个数字。您可以更改数字是否不止一个,例如\d+
  • (Dist_\d_)- 表示第三个捕获组匹配Dist_字面后跟一个数字。
  • (.*)- 表示贪婪之后匹配所有内容的第四个捕获组。
  • $1$3$2$4- 对于更换零件交换组$3$2获得所需的结果。

图片表示

您可以在此处找到上述正则表达式的演示

用于重命名文件的 Powershell 命令:

PS C:\Path\To\MyDesktop\Where\Files\Are\Present> Get-ChildItem -Path . -Filter *.txt | Foreach-Object {
>>   $_ | Rename-Item -NewName ( $_.Name -Replace '(.*?)(ND_\d_)(Dist_\d_)(.*)', '$1$3$2$4' )
>> }     
Run Code Online (Sandbox Code Playgroud)

上面命令的解释:

1. Get-ChildItem - The Get-ChildItem cmdlet gets the items in one or more specified locations
2. -Path . - Represents a flag option for checking in present working directory.
3. -Filter *.txt - Represents another flag option which filters all the .txt files in present working directory.
4. Foreach-Object - Iterate over objects which we got from the above command.
    4.1. Rename-Item -NewName - Rename each item 
         4.2. $_.Name -Replace - Replace the name of each item containing regex pattern with the replacement pattern.
5. end of loop
Run Code Online (Sandbox Code Playgroud)