Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell trim - remove all characters after a string

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
like image 951
samsux Avatar asked Mar 17 '15 00:03

samsux


People also ask

How do I trim a string in PowerShell?

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.

How do I remove part of a string in PowerShell?

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.

How do you get a string after a specific character in PowerShell?

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.

How do I use TrimStart in PowerShell?

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.


2 Answers

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. )

like image 161
LinkBerest Avatar answered Sep 19 '22 11:09

LinkBerest


Using -replace

(Get-Content $file -Raw) -replace '(?s)\\test\.something\\.+' | Set-Content $file
like image 43
mjolinor Avatar answered Sep 18 '22 11:09

mjolinor