What would be the command to remove everything after a string (\test.something). I have information in a text file, but after the string there is like a 1000 lines of text that I don't want. how can I remove everything after and including the string.
This is what I have - not working. Thank you so much.
$file = get-item "C:\Temp\test.txt"
(Get-Content $file) | ForEach {$_.TrimEnd("\test.something\")} | Set-Content $file
One of the most common ways to trim strings in PowerShell is by using the trim() method. Like all of the other trimming methods in PowerShell, the trim() method is a member of the System. String . NET class.
Remove First Character from the String in PowerShell To remove the first character from the string in PowerShell, use the remove() method. The remove method takes two arguments to remove the first character from the string. startIndex: Specify the start index to begin deleting the character.
To get PowerShell substring after a character in the given string, use the IndexOf method over the string to get the position of the character. Use the position in PowerShell substring as the start index to get a substring. PowerShell substring() method returns the part of the string.
TrimStart([Characters_to_remove]) Key Characters_to_remove The characters to remove from the beginning and/or end of the string. Multiple characters can be specified. The order of the characters does not affect the result. By default trim() will remove leading and trailing spaces and leading and trailing line breaks.
Why remove everything after? Just keep everything up to it (I'm going to use two lines for readability but you can easily combine into single command):
$text = ( Get-Content test.txt | Out-String ).Trim()
#Note V3 can just use Get-Content test.txt -raw
$text.Substring(0,$text.IndexOf('\test.something\')) | Set-Content file2.txt
Also, you may not need the Trim but you were using TrimEnd so added in case you want to add it later. )
Using -replace
(Get-Content $file -Raw) -replace '(?s)\\test\.something\\.+' | Set-Content $file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With