Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell to remove text from a string

Tags:

What is the best way to remove all text in a string after a specific character? In my case "=" and after another character in my case a ,, but keep the text between?

Sample input

=keep this,

like image 960
JoeRod Avatar asked Oct 03 '13 20:10

JoeRod


People also ask

How do I strip text 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.

What does TRIM () do in PowerShell?

PowerShell Trim() methods (Trim(), TrimStart() and TrimEnd()) are used to remove the leading and trailing white spaces and the unwanted characters from the string or the raw data like CSV file, XML file, or a Text file that can be converted to the string and returns the new string. These methods are part of the System.

How do I modify a string in PowerShell?

One of the easiest ways to replace strings in PowerShell replace command method as shown below. The replace() method has two arguments; the string to find and the string to replace the found text with. As you can see below, PowerShell is finding the string hello and replacing that string with the string hi .

How do I Remove special characters from a string in PowerShell?

Use the -Replace Operator to Escape Special Characters in PowerShell. The -Replace operator replaces texts or characters in PowerShell. You can use it to remove texts or characters from the string. The -Replace operator requires two arguments: the string to find and the string to replace from the given input.


1 Answers

Another way to do this is with operator -replace.

$TestString = "test=keep this, but not this."  $NewString = $TestString -replace ".*=" -replace ",.*" 

.*= means any number of characters up to and including an equals sign.

,.* means a comma followed by any number of characters.

Since you are basically deleting those two parts of the string, you don't have to specify an empty string with which to replace them. You can use multiple -replaces, but just remember that the order is left-to-right.

like image 103
Benjamin Hubbard Avatar answered Sep 18 '22 15:09

Benjamin Hubbard