1

The following code removes the ! from all the .txt files.

get-childitem *.txt | ForEach {Move-Item -LiteralPath $_.name $_.name.Replace("!","")}

I need to do this not only for the ! character but also for #, ,, ~, among others. My intention is to get a code that has the following rule: any character other than [a-z] and also [0-9] must be removed from the file names.

John Lima
  • 85
  • 4

1 Answers1

1

Assuming you want to rename the files in place:

Get-Childitem *.txt | Rename-Item -WhatIf -NewName { 
  ($_.BaseName -replace '[^\d\p{L}]') + $_.Extension 
}

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.

  • For renaming files in place, it is better to use Rename-Item than Move-Item.

  • Note that Rename-item is directly piped to, with the new file names getting dynamically calculated via a delay-bind script block.

  • Negated (^) character set ([...]) \d\p{L} matches all characters that are neither digits (\d) nor letters (p{L}).

    • Note:
      • p{L} also matches letters outside the ASCII range of Unicode characters, such as é, for instance; if you really want to limit matching to ASCII-range letters only, use a-z
      • Similarly, \d matches not just 0 through 9, but other Unicode characters that are considered digits (e.g., (BENGALI DIGIT EIGHT, U+09EE); to limit matching to 0 through 9, use 0-9.
    • PowerShell by default is case-insensitive, so if you wanted to match lowercase letters only, you'd have to use -creplace and p{Ll}.
  • By not specifying a replacement string, all matching characters are effectively removed.

mklement0
  • 382,024
  • 64
  • 607
  • 775