Joe
Joe

Reputation: 25

Translation from Powershell to Python

I'm working on a simple script I have used to work/edit a large folder with movies/tv-shows and I have found an easy way to remove certain strings in folder and file titles, but it is a PowerShell command and I have the rest of my functions in a Python script.

  1. First, I'm asking for someone who might be able to make a Python equivalent to this PowerShell line:

    Get-ChildItem -Recurse | Where-Object {$_.Name -match 'SomeString'} | Rename-Item -NewName {$_.Name -replace 'SomeString', ''}
    
  2. Second, I have experienced issues with the PowerShell command if the string I want removed contains the [] (like this: -[Something]) - the titles will become unreadable and I'm not sure why.

Upvotes: 0

Views: 1095

Answers (2)

Joe
Joe

Reputation: 25

This solved my problems and works for me. Thanks to JosefZ who showed how Regex.Escape method was used.

$dir = 'C:\Users\user\Desktop\folder'
CD $dir
$SomeString = '-[String.String]'
$SafeString = [regex]::Escape( $SomeString )
Get-ChildItem -Recurse | Where-Object {$_.Name -match $SafeString} | Rename-Item -NewName {$_.Name -replace $SafeString, ''}

This will remove all -[String.String] from any folder and file title in the path.

Upvotes: 0

JosefZ
JosefZ

Reputation: 30153

Although the double-backtick approach could work, I'd recommend Regex.Escape method. Safe and useful if a string to be escaped comes from an external source.

Regex.Escape(String) Method

Escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $, ., #, and white space) by replacing them with their escape codes. This instructs the regular expression engine to interpret these characters literally rather than as metacharacters.

Example:

$SomeString = '[square]'
$SafeString = [regex]::Escape( $SomeString )
Get-ChildItem -Recurse | 
    Where-Object { $_.Name -match $SafeString } | 
    ForEach-Object { $_ | 
        Rename-Item -NewName $($_.Name -replace $SafeString, '')  -WhatIf
    }

Result:

PS D:\PShell> D:\PShell\SO\53619911.ps1
What if: Performing the operation "Rename File" on target "Item: D:\PShell\DataFi
les\some[square]file.txt Destination: D:\PShell\DataFiles\somefile.txt".
What if: Performing the operation "Rename File" on target "Item: D:\PShell\DataFi
les\some[square]file2.txt Destination: D:\PShell\DataFiles\somefile2.txt".

Upvotes: 1

Related Questions