How can I extract a substring using PowerShell?
I have this string ...
"-----start-------Hello World------end-------"
I have to extract ...
Hello World
What is the best way to do that?
Use the Substring() Method to Extract a Substring in PowerShell. We can use the Substring() method to find a string inside a string. For example, perhaps we have a string like 'Hello World is in here Hello World!' and you'd like to find the first four characters.
When you need to search through a string or log files in Linux we can use the grep command. For PowerShell, we can use the grep equivalent Select-String . We can get pretty much the same results with this powerful cmdlet. Select-String uses just like grep regular expression to find text patterns in files and strings.
You can use Select-String similar to grep in UNIX or findstr.exe in Windows. Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.
The -match
operator tests a regex, combine it with the magic variable $matches
to get your result
PS C:\> $x = "----start----Hello World----end----" PS C:\> $x -match "----start----(?<content>.*)----end----" True PS C:\> $matches['content'] Hello World
Whenever in doubt about regex-y things, check out this site: http://www.regular-expressions.info
The Substring
method provides us a way to extract a particular string from the original string based on a starting position and length. If only one argument is provided, it is taken to be the starting position, and the remainder of the string is outputted.
PS > "test_string".Substring(0,4) Test PS > "test_string".Substring(4) _stringPS >
But this is easier...
$s = 'Hello World is in here Hello World!' $p = 'Hello World' $s -match $p
And finally, to recurse through a directory selecting only the .txt files and searching for occurrence of "Hello World":
dir -rec -filter *.txt | Select-String 'Hello World'
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