Issue
I have multiple files named in this format:
Fat1920OVXPlacebo_S20_R1_001.fastq
Kidney1235SHAM_S65_R1_001.fastq
Kidney1911OVXPlacebo_S94_R2_001.fastq
Liver1289OVXEstrogen_S24_R2_001.fastq
I need to insert the string "L1000_" into their names so that they read
Fat1920OVXPlacebo_S20_L1000_R1_001.fastq
Kidney1235SHAM_S65_L1000_R1_001.fastq
Kidney1911OVXPlacebo_S94_L1000_R2_001.fastq
Liver1289OVXEstrogen_S24_L1000_R2_001.fastq
I apologize but I have absolutely no experience in coding in powershell. The closest thing I could find to do this was a script that renames the entire file:
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set Folder = objFSO.GetFolder(“ENTER\PATH\HERE”)
For Each File In Folder.Files
sNewFile = File.Name
sNewFile = Replace(sNewFile,”ORIGINAL”,”REPLACEMENT”)
if (sNewFile<>File.Name) then
File.Move(File.ParentFolder+”\”+sNewFile)
end if
Next
however, I just need to insert a string at a specific place in the file’s title. I have 257 files and do not want to go 1 by 1. Does anyone have an idea on how to run this in windows?
Solution
Use Get-ChildItem
to enumerate the files of interest, pipe them to Rename-Item
, and use a delay-bind script block ({ ... }
) to dynamically determine the new name, via a regex-based -replace
operation.
(Get-ChildItem $yourFolder -Filter *.fastq) |
Rename-Item -NewName { $_.Name -replace '(?<=_S\d+_)', 'L1000_' } -WhatIf
Note:
• The -WhatIf
common parameter in the command above previews the operation. Remove -WhatIf
once you’re sure the operation will do what you want.
• Even though not strictly necessary in this case, enclosing the Get-ChildItem
command in (...)
, the grouping operator ensures that already renamed files don’t accidentally re-enter the enumeration of files to be renamed – see this answer.
-
(?<=_S\d+_)
uses a positive look-behind assertion ((?<=...)
) to match verbatim string_S
, followed by one or more (+
) digits (\d
), followed by verbatim_
. -
Since the look-behind assertion merely matches a position in the string rather than a substring, the replacement operand, verbatim
L1000_
in this case, is inserted at that position in (a copy of) the input string. -
For a more detailed explanation of the delay-bind script-block technique, see this answer.
Answered By – mklement0
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0