Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell regex group replacing

I want to replace some text in every script file in folder, and I'm trying to use this PS code:

$pattern = '(FROM [a-zA-Z0-9_.]{1,100})(?<replacement_place>[a-zA-Z0-9_.]{1,7})'
Get-ChildItem -Path 'D:\Scripts' -Recurse -Include *.sql | ForEach-Object { (Get-Content $_.fullname) -replace $pattern, 'replace text' | Set-Content $_.fullname }

But I have no idea how to keep first part of expression, and just replace the second one. Any idea how can I do this? Thanks.

like image 748
hmnzr Avatar asked Aug 03 '12 10:08

hmnzr


People also ask

How does replace work in PowerShell?

Using the Replace() MethodThe 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 . The method then returns the final result which is hi, world .

What is $1 PowerShell?

$& is the overall regex match, $1 is the text matched by the first capturing group, and ${name} is the text matched by the named group “name”.

How do you replace content in PowerShell?

Use Get-Content and Set-Content to Replace Every Occurrence of a String in a File With PowerShell. The Get-Content gets the item's content in the specified path, such as the text in a file. The Set-Content is a string-processing cmdlet that allows you to write new content or replace the existing content in a file.


1 Answers

Not sure that provided regex for tables names is correct, but anyway you could replace with captures using variables $1, $2 and so on, and following syntax: 'Doe, John' -ireplace '(\w+), (\w+)', '$2 $1'

Note that the replacement pattern either needs to be in single quotes ('') or have the $ signs of the replacement group specifiers escaped ("`$2 `$1").

# may better replace with     $pattern = '(FROM) (?<replacement_place>[a-zA-Z0-9_.]{1,7})'
$pattern = '(FROM [a-zA-Z0-9_.]{1,100})(?<replacement_place>[a-zA-Z0-9_.]{1,7})'

Get-ChildItem -Path 'D:\Scripts' -Recurse -Include *.sql | % `
{
   (Get-Content $_.fullname) | % `
     { $_-replace $pattern, '$1 replace text' } | 
     Set-Content $_.fullname -Force
}

If you need to reference other variables in your replacement expression (as you may), you can use a double-quoted string and escape the capture dollars with a backtick

     { $_-replace $pattern, "`$1 replacement text with $somePoshVariable" } | 
like image 64
Akim Avatar answered Sep 28 '22 02:09

Akim