Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I delete certain characters or replace certain characters with other characters by some batch file execution, for filenames of all files in a Windows folder in one go, is there a DOS command for that?

like image 762
VSS Avatar asked May 19 '13 16:05

VSS


People also ask

How do I rename multiple files or delete multiple characters?

Click the Select all button. Quick tip: Alternatively, you can also use the Ctrl + A keyboard shortcut to select all files. You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.

How do I trim multiple file names?

Press CTRL + A to select all the files in the folder, then right-click and select Rename. Input your new file name, and press Enter.


3 Answers

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 " ","_" }
    
like image 140
Ravi K Thapliyal Avatar answered Oct 11 '22 07:10

Ravi K Thapliyal


A one-liner command in Windows PowerShell to delete or rename certain characters will be as below. (here the whitespace is being replaced with underscore)

Dir | Rename-Item –NewName { $_.name –replace " ","_" }
like image 35
aphoe Avatar answered Oct 11 '22 08:10

aphoe


The PowerShell answers are good, but the Rename-Item command doesn't work in the same target directory unless ALL of your files have the unwanted character in them (fails if it finds duplicates).

If you're like me and had a mix of good names and bad names, try this script instead (will replace spaces with an underscore):

Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace(" ", "_") }
like image 19
Dustin Malone Avatar answered Oct 11 '22 09:10

Dustin Malone