Reputation: 307
I have a list of users in a text file who's names are in the following format: xn-tsai-01.
How do I script to remove the xn- KEEP THIS -01 so the output is like: tsai
I know how to do this in bash but not too familiar with powershell.
Thanks in advance!
Upvotes: 1
Views: 38329
Reputation: 71
Why not use Substring method. If you will always trim the first three characters, you can do the following assuming the variable is a string type.
$string = xn-tsai-01
$string.Substring(3)
Upvotes: 7
Reputation: 209
Boe's example is probably going to be the most efficient.
Another way is to use the split()
method if they're in a uniform format.
Get-Content .\list.txt | % { ($_.Split('-'))[1] }
% is an alias for ForEach
Upvotes: 2
Reputation: 1868
Here is a quick way to do it using regex:
'xn-tsai-01' -replace '.*?-(.*)-.*','$1'
Example with a list:
(Get-Content list.txt) -Replace '.*?-(.*)-.*','$1'
Upvotes: 3
Reputation: 174515
You can use the .NET string method IndexOf("-")
to find the first, and LastIndexOf("-")
to find the last occurrence of "-" within the string.
Use these indexes with Substring()
to remove the unnecessary parts:
function Clean-Username {
param($Name)
$FirstDash = $Name.IndexOf("-") + 1
$LastDash = $Name.LastIndexOf("-")
return $Name.Substring( $f, $l - $f )
}
PS C:\> Clean-UserName -Name "xn-tsai-01"
tsai
Upvotes: 2