Reputation: 21
I have a set of files in a folder. I would like to edit all file names by moving part of the file name to a different position. That is a sample of what I have:
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
that is what I want:
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
Basically, I want to place "ND_(number)" after "Dist_(number)
Thank you for your help.
Upvotes: 2
Views: 557
Reputation:
You may try:
(.*?)(ND_\d_)(Dist_\d_)(.*)
Explanation of the above regex:
(.*?)
- Represents first capturing group lazily matching everything before ND
.(ND_\d_)
- Represents second cpaturing group matching ND_
followed by a digit. You can alter if digits are more than one like \d+
.(Dist_\d_)
- Represents third capturing group matching Dist_
literally followed by a digit.(.*)
- Represents fourth capturing group matching everything after greedily.$1$3$2$4
- For the replacement part swap groups $3
and $2
to get your required result.You can find the demo of the above regex in here.
Powershell Command for renaming the files:
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' )
>> }
Explanation of the above command:
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
Upvotes: 6