Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove character from file name in powershell

Tags:

powershell

I'm new to powershell and wanted to know if there's a way to remove a character from a file name. The character I'm trying to remove is a dash "-" and sometimes there are 2 or 3 dashes in the file name. Is it possible to have it rename files that have a dash in them?

like image 689
Noesis Avatar asked Dec 08 '22 20:12

Noesis


2 Answers

Get-Item .\some-file-with-hyphens.txt | ForEach-Object {
  Rename-Item $_ ($_.Name -replace "-", "")
}

This question may be more suitable for SuperUser.

like image 51
Ansgar Wiechers Avatar answered Feb 09 '23 07:02

Ansgar Wiechers


To remove or replace characters in a file name use single quotes ' and for "special" characters escape them with a backslash \ so the regular expression parser takes it literally.

The following removes the $ (dollar sign) from all file names in your current directory:

Get-Item * | ForEach-Object { rename-item $_ ($_.Name -replace '\$', '') }

the following is the same as above using the shorter alias for each command:

gi * | % { rni $_ ($_.Name -replace '\$', '') }

The following is removing the standard character "Z" from all file names in your current directory:

gi * | % { rni $_ ($_.Name -replace 'Z', '') }
like image 36
Invictuz Avatar answered Feb 09 '23 06:02

Invictuz