Find and Replace a Word with Another in All File Names of a Directory

Search and replace file names according to strings in dataframe. In R

You can create a named vector of replacement and pattern and use it in str_replace_all

files <- list.files(directory)
files <- stringr::str_replace_all(files, setNames(df$sample, df$well))

Using a reproducible example -

df <- structure(list(well = c("A1", "B1", "C1"), sample = c("F32-1", 
"F13-3", "B11-4")), class = "data.frame", row.names = c(NA, -3L))

files <- c("blabla_A1_bla.txt", "blabla_A1_bla.phd","blabla_B1_bla.txt", "blablabla_B1_bla.phd")

stringr::str_replace_all(files, setNames(df$sample, df$well))
#[1] "blabla_F32-1_bla.txt" "blabla_F32-1_bla.phd" "blabla_F13-3_bla.txt"
#[4] "blablabla_F13-3_bla.phd"

Search file names from one list and replace them with another list in BATCH

As per my comment. Create a single file called names.txt and add the strings you want to replace and what you want to replace it with:

dummy replacement
dummy2 replacement2

then the script needs to be in the same directory, or you have to specify path to the files:

@echo off
setlocal enabledelayedexpansion
for /f "tokens=1,2" %%i in (names.txt) do (
for /f %%a in ('dir /b /a-d ^| findstr "%%i"') do (
set "oldname=%%a"
set "newname=!oldname:%%i=%%j!"
echo ren "!oldname!" "!newname!"
)
)

or by specifying path:

@echo off
setlocal enabledelayedexpansion
for /f "tokens=1,2" %%i in (names.txt) do (
for /f %%a in ('dir /b /a-d "D:\PATH" ^| findstr "%%i"') do (
set "oldname=%%a"
set "newname=!oldname:%%i=%%j!"
echo ren "!oldname!" "!newname!"
)
)

Once you are happy that it prints the files to replace to screen, simply remove the echo from the last line of code to actually perform the ren

Replace or delete certain characters from filenames of all files in a folder

Use PowerShell to do anything smarter for a DOS prompt. Here, I've shown how to batch rename all the files and directories in the current directory that contain spaces by replacing them with _ underscores.

Dir |
Rename-Item -NewName { $_.Name -replace " ","_" }

EDIT :
Optionally, the Where-Object command can be used to filter out ineligible objects for the successive cmdlet (command-let). The following are some examples to illustrate the flexibility it can afford you:

  • To skip any document files

    Dir |
    Where-Object { $_.Name -notmatch "\.(doc|xls|ppt)x?$" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
  • To process only directories (pre-3.0 version)

    Dir |
    Where-Object { $_.Mode -match "^d" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }

    PowerShell v3.0 introduced new Dir flags. You can also use Dir -Directory there.

  • To skip any files already containing an underscore (or some other character)

    Dir |
    Where-Object { -not $_.Name.Contains("_") } |
    Rename-Item -NewName { $_.Name -replace " ","_" }

Command Prompt Replace a String in the Middle of Filenames

I found a better solution that works for me. One line, no batch file required. Using Windows Power Shell, enter:

Get-ChildItem -Recurse | ` Where-Object { $_.Name -match " - " } | ` Rename-Item -NewName { $_.Name -replace " - ", " " }

The above command will replace the given text in all filenames, including subfolders and subfiles (recursively).

I hope it's able to help someone.

How do I find and replace all occurrences (in all files) in Visual Studio Code?

Since version 1.3 of vscode this is possible

  1. Navigate to the search, click icon to the left or:
    • (mac) cmd + shift + h
    • (PC) ctrl + shift + h
  2. expand replace
  3. enter search term and replace term
  4. confirm!

Search and replace with vscode

Mass Find & Replace including subfolders

«I need pop-up windows as described in my original post. I'm not familiar enough with this stuff to make changes» For example:

Option Explicit
Dim FSO As Object, oFolder As Object, StrFolds As String, StrFnd As String, StrRep As String

Sub Main()
Dim TopLevelFolder As String, TheFolders As Variant, aFolder As Variant, i As Long
StrFnd = InputBox("Enter finding text here:")
If StrFnd = "" Then Exit Sub
StrRep = InputBox("Enter replacing text here:")
TopLevelFolder = GetFolder
If TopLevelFolder = "" Then Exit Sub
StrFolds = vbCr & TopLevelFolder
If FSO Is Nothing Then
Set FSO = CreateObject("Scripting.FileSystemObject")
End If
'Get the sub-folder structure
Set TheFolders = FSO.GetFolder(TopLevelFolder).SubFolders
For Each aFolder In TheFolders
RecurseWriteFolderName (aFolder)
Next
'Process the documents in each folder
For i = 1 To UBound(Split(StrFolds, vbCr))
Call UpdateDocuments(CStr(Split(StrFolds, vbCr)(i)))
Next
End Sub


Sub RecurseWriteFolderName(aFolder)
Dim SubFolders As Variant, SubFolder As Variant
Set SubFolders = FSO.GetFolder(aFolder).SubFolders
StrFolds = StrFolds & vbCr & CStr(aFolder)
On Error Resume Next
For Each SubFolder In SubFolders
RecurseWriteFolderName (SubFolder)
Next
End Sub

Sub UpdateDocuments(oFolder As String)
Application.ScreenUpdating = False
Dim strInFolder As String, strFile As String, wdDoc As Document
strInFolder = oFolder
strFile = Dir(strInFolder & "\*.doc", vbNormal)
While strFile <> ""
Set wdDoc = Documents.Open(FileName:=strInFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
With wdDoc
With .Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Text = StrFnd
.Replacement.Text = StrRep
.Execute Replace:=wdReplaceAll
End With
'Save and close the document
.Close SaveChanges:=True
End With
strFile = Dir()
Wend
Set wdDoc = Nothing
Application.ScreenUpdating = True
End Sub

Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function

As coded, the macro will process .doc, .docx, and .docm files. To limit it to .docx files, change the .doc reference to .docx.

Replace certain characters from filenames in all files in a folder and his sub-folders

Your own answer will only change one char, here is a solution with an array RegEx in one go, remove the chars you want to keep from $replace.

[char[]]$replace = '!@#$%^&*(){}[]":;,<>/|\+=`~ '''
$regex = ($replace | % {[regex]::Escape($_)}) -join '|'

Get-ChildItem -recurse |
ForEach {
if ($_.Name -match $RegEx){
Ren $_.Fullname -NewName $($_.Name -replace $RegEx, '_') -whatif
}
}

If the output looks ok, remove the -whatif

Edit removed -File option from Get-ChildItem as it requires a recent Powershell version and wasn't necessary.

Edit2 I regularly state that Rename-Item accepts piped input, so here is a more straight forward version:

[char[]]$replace = '!@#$%^&*(){}[]":;,<>/|\+=`~ '''
$regex = ($replace | % {[regex]::Escape($_)}) -join '|'
Get-ChildItem -recurse |
Where-Object { $_.Name -match $RegEx} |
Rename-Item -NewName {$_.Name -replace $RegEx, '_'} -whatif


Related Topics



Leave a reply



Submit