Replace first character in a string with TrimStart

2 minutes to read


The requirement for this task was clear, also focused miscellaneous methods, one of these was to use a regular expression, of course, wasn’t impressed. I have to focus on the time of execution because this script it’s been going to process files with the size of 10 Mb+. Found TrimStart that is perfect for my scenario:

> Replace the first character in a string with PowerShell. In my case the string is: “|”, and the all the strings looks like below: I have to cut just first string if it equal with  “|”.

|-/A1101 |A|param,string,egal|A1|A11|margin-right:11px;font-size:10px;¤
|-/A1102 |A|param,string,egal|A1|A11|margin-right:11px;font-size:10px;¤
-/A1103 |A|param,string,egal|A1|A11|margin-right:11px;font-size:10px;¤
|-/A1104 |A|param,string,egal|A1|A11|margin-right:11px;font-size:10px;¤
-*/A1105 |A|param,string,egal|A1|A11|margin-right:11px;font-size:10px;¤

Solution: In first line we upload the content of file1.txt to $content, after that with $content.TrimStart cut the “|” , the results will be in $contenttrim and exported to file1-output.txt, commands below: 
PS C:\Users\cloudtech> $content = Get-Content C:\content\file1.txt
PS C:\Users\cloudtech> $contenttrim = $content.TrimStart("|"," ")
PS C:\Users\cloudtech> $contenttrim | Out-File C:\content\file1-output.txt

Output: The output of $contenttrim  
-/A1101 |A|param,string,egal|A1|A11|margin-right:11px;font-size:10px;¤<br />
-/A1102 |A|param,string,egal|A1|A11|margin-right:11px;font-size:10px;¤<br />
-/A1103 |A|param,string,egal|A1|A11|margin-right:11px;font-size:10px;¤<br />
-/A1104 |A|param,string,egal|A1|A11|margin-right:11px;font-size:10px;¤<br />
-*/A1105 |A|param,string,egal|A1|A11|margin-right:11px;font-size:10px;¤
Remarks: The TrimStart method removes from the current string all leading characters that are in the trimChars parameter. The trim operation stops when a character that is not in trimChars is encountered. For example, if the current string is “123abc456xyz789” and trimChars contains the digits from “1” through “9”, the TrimStart method returns “abc456xyz789”.

If you have some doubts/recommendations, related scenario vs solution don’t hesitate to write in a comment.

Leave a Reply

Your email address will not be published.Required fields are marked *