How to -remove multiple items at once?

徘徊边缘 提交于 2019-12-13 06:34:57

问题


I currently have a list of 25,000+ server names. Each name has a ton of extra stuff added on to the name, which I want to remove. Here is a sample data:

WindowsAuthServer @{htew804WIN}

I want to remove "WindowsAutherServer @{" and "WIN}" from each server, leaving just "htew804" left. I currently have:

$remove1 = $file -remove "WindowsAutherServer @{",""
$final = $remove1 -remove "WIN}",""

This works, but I would like to do it all in one step if possible. Can this be done?


回答1:


This RegEx could do it in one go:

$str = "WindowsAuthServer @{htew804WIN}"
$str -replace '.*?{(.*?)WIN}','$1'



回答2:


Think about what you want to keep instead.

"WindowsAuthServer @{htew804WIN}" | foreach { $x = $_ -match '\@\{(.+)WIN}' ; $Matches[1] }



回答3:


This can easily be done using String.Substring() and String.LastIndexOf() methods:

$str = "WindowsAuthServer @{htew804WIN}"
$str.Substring(($open = $str.LastIndexOf('{') + 1), $str.LastIndexOf('}') - $open - 3)

We first use String.LastIndexOf('{') to find the last occurrence of {, then (using that as an offset) calculate the length until just before WIN}




回答4:


Or this one:

$str = "WindowsAuthServer @{htew804WIN}"
([regex]'@\{(\w+)WIN\}').Match($str).Groups[1].Value;


来源:https://stackoverflow.com/questions/53834831/how-to-remove-multiple-items-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!