【问题标题】:Issue with String Manipulation in Powershell TrimEnd()Powershell TrimEnd() 中的字符串操作问题
【发布时间】:2016-08-09 15:49:14
【问题描述】:

我有这个重命名文件的 PowerShell 脚本。以下是字符串操作代码的一部分(不是我的实际代码,只是为了说明问题):

$text="String1.txt"
$text
$text.trimend(".txt")
$date=Get-Date -format yyyyMMdd
$text + $date
$newFile = $text.trimend(".txt") + "_" + $date + ".bak"
$newFile
$NewFile1 = $newFile.TrimEnd("_$date.bak") + ".bak"
$NewFile1

结果是:

String1.txt
String1
String1.txt20131104
String1_20131104.bak
String.bak

为什么String1 末尾的1 也被删除了?我希望结果是String1.bak

【问题讨论】:

    标签: string powershell


    【解决方案1】:

    trimend() 方法接受一个字符数组(不是字符串)参数,并将修剪数组中出现在字符串末尾的所有字符。

    我通常使用 -replace 运算符来修剪字符串值:

    $text="String1.txt"
    $text 
    $text = $text -replace '\.txt$',''
    $text
    
    String1.txt
    String1
    

    【讨论】:

      【解决方案2】:

      PowerShell to remove text from a string 的答案上进行开发,我正在使用这些正则表达式来修剪未知类型的扩展名,文件名中的其他位置可能带有.

      $imagefile="hi.there.jpg"
      $imagefile
      hi.there.jpg
      $imagefile -replace '\.([^.]*)$', ''
      hi.there
      $imagefile -replace '([^.]*)$', ''
      hi.there.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-31
        • 2023-03-22
        • 1970-01-01
        • 2021-12-19
        • 1970-01-01
        • 1970-01-01
        • 2010-12-30
        相关资源
        最近更新 更多