简体   繁体   中英

Issue with String Manipulation in Powershell TrimEnd()

I have this PowerShell script that renames a file. The following is part of the string manipulation code (not my actual code, just to show the issue):

$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

The result is:

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

Why was the 1 at the end of String1 removed as well? I am expecting the result to be String1.bak .

The trimend() method takes a character array (not string) argument, and will trim all of the characters in the array that appear at the end of the string.

I usually use the -replace operator for trimming off a string value:

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

String1.txt
String1

Developing on the answer at PowerShell to remove text from a string , I'm using these regex's to trim off an extension of unkown type with possible . elsewhere in the filename:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM