Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a substring using PowerShell

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?

like image 676
achi Avatar asked Jun 07 '10 10:06

achi


People also ask

How do I extract a Substring in PowerShell?

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.

Can you grep in PowerShell?

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.

How do I find a word in a text file using PowerShell?

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.


2 Answers

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

like image 161
Matt Woodard Avatar answered Sep 20 '22 02:09

Matt Woodard


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' 
like image 35
nineowls Avatar answered Sep 19 '22 02:09

nineowls