简体   繁体   中英

How to remove part of the string in powershell?

Here is a list of projects, around 300 lines. I want to cut off (ID: ...) from each line using PowerShell.

Currently, I have:

BlockService API (ID: Projects-1)
BlockService 1 (ID: Projects-903)
CheckService ScheduledJob (ID: Projects-620)
Checkout Archibus (ID: Projects-96)
BackOffice Service (ID: Projects-12)

And I need to get:

BlockService API
BlockService 1
CheckService ScheduledJob
Checkout Archibus
BackOffice Service

I/m not sure how to do with TrimStart and TrimEnd as I can't get desired results...any advice?

You can replace parts of string using regex in PowerShell:

$s = "BlockService API (ID: Projects-1)"
$s -replace "\(ID.*\)",""

or

"BlockService API (ID: Projects-1)" -replace "\(ID.*\)",""

I'm not sure why you would like to use Trim methods. If you have the projects in projects.txt text file, you could do with this instead:

Get-Content ".\projects.txt" | ForEach-Object {($_ -split " \(ID:")[0]}

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