Reputation: 53
In PowerShell I have a string with a value similar to :
> text/text/text\text\text\text
The string is variable length, and may have different numbers of forward and back slashes.
I want to insert a colon (:
) character before the first backslash only. So change it from ...
> text/text/text\text\text\text
to ...
> text/text/text:\text\text\text
What's the simplest way to do this?
Thanks
Upvotes: 5
Views: 12130
Reputation: 174690
Use the Insert()
and IndexOf()
string methods:
$string = 'text/text/text\text\text\text'
$result = $string.Insert($string.IndexOf('\'),':')
Reports the zero-based index of the first occurrence of the specified string in this instance.
while String.Insert()
:
Returns a new string in which a specified string is inserted at a specified index position in this instance.
With PowerShell 3.0+ you can also easily use regular expressions to insert the :
:
$result = $string -replace '(?<!\\.*)\\',':\'
Upvotes: 5
Reputation: 23385
I was going to suggest this but Mathias' answer is better:
$text = 'text/text/text\text\text\text'
$bs = $text.IndexOf('\')
"$($text.Substring(0,$bs)):$($text.Substring($bs))"
Upvotes: 1