【问题标题】:Translation from Powershell to Python从 Powershell 到 Python 的翻译
【发布时间】:2018-12-04 19:12:35
【问题描述】:

我正在编写一个简单的脚本,我曾经用它来处理/编辑带有电影/电视节目的大文件夹,并且我找到了一种删除文件夹和文件标题中某些字符串的简单方法,但它是一个 PowerShell 命令我的其余函数都在 Python 脚本中。

  1. 首先,我想请教一个能够制作与此 PowerShell 行等效的 Python 的人:

    Get-ChildItem -Recurse | Where-Object {$_.Name -match 'SomeString'} | Rename-Item -NewName {$_.Name -replace 'SomeString', ''}
    
  2. 其次,如果我要删除的字符串包含 [](例如:-[Something]),我遇到了 PowerShell 命令的问题 - 标题将变得不可读,我不知道为什么。

【问题讨论】:

标签: python powershell


【解决方案1】:

虽然双反引号方法可行,但我推荐Regex.Escape 方法。如果要转义的字符串来自外部源,则安全且有用。

Regex.Escape(String) Method

转义最少的字符集\*+?|{、@987654331 @、()^$.#空白)通过替换 他们用他们的转义码。这指示正则表达式 引擎从字面上解释这些字符而不是 元字符。

示例

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

结果

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".

【讨论】:

    【解决方案2】:

    这解决了我的问题并为我工作。感谢 JosefZ 展示了如何使用 Regex.Escape 方法。

    $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, ''}
    

    这将从路径中的任何文件夹和文件标题中删除所有 -[String.String]。

    【讨论】:

      猜你喜欢
      • 2022-10-17
      • 2018-09-16
      • 2019-10-07
      • 1970-01-01
      • 2022-01-18
      • 2019-07-09
      • 2021-09-26
      • 1970-01-01
      • 2014-02-22
      相关资源
      最近更新 更多