简体   繁体   中英

how to use regular expression replacement in PowerShell

ipconfig | Select-String "IPv4 Address" ipconfig | Select-String "IPv4 Address" returns something like this:

   IPv4 Address. . . . . . . . . . . : 192.168.1.50
   IPv4 Address. . . . . . . . . . . : 172.20.112.1
   IPv4 Address. . . . . . . . . . . : 192.168.208.1

Say I wanted to replace "IPv4 Address. . . . . . . . . . . :" with the empty string using -replace . How would I do that? Here's what I tried:

ipconfig | Select-String "IPv4 Address" -replace "IPv4 Address. . .",""

That gave me the following error:

Select-String : A parameter cannot be found that matches parameter name 'replace'.
At line:1 char:41
+ ipconfig | Select-String "IPv4 Address" -replace "IPv4 Address. . .", ...
+                                         ~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Select-String], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SelectStringCommand

Any ideas?

You can use

ipconfig | Select-String "IPv4 Address" | foreach { $_ -replace '.*:\s*' }

With .*:\s* , you match all text up to the last : on a line and \s* also consumes any zero or more whitespace chars after than colon.

Here is the regex demo .

Using only Select-String , you can can use a capture group to extract the IP-address:

ipconfig | Select-String "IPv4 Address.*:\s*(.+)" | ForEach-Object { $_.Matches.Groups[1].Value }
  • .*: matches everything up to the :
  • \s* matches any (zero or more) whitespace between : and IP-address
  • (.+) matches the IP-address (one more more char) and captures it in group 1
  • $_.Matches.Groups[1].Value outputs the value of capture group 1, which is the IP-address

This link gives a good overview about the many possibilities of using RegEx with PowerShell.

Install Git. Start Git Bash and use grep and sed (or cut or awk ):

$ ipconfig | grep 'IPv4 Address' | sed 's/.*: //'

s/xyz/abc/ means s ubstitute xyz with abc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM