Home > Blockchain >  Modify a number following a certain structure in powershell
Modify a number following a certain structure in powershell

Time:01-19

In powershell, i'm trying to replace the first number of each phone number with 0. One way to find the phone number is to search for numbers with 10 digits followed by , thats what i did below. The problem is that those phone numbers are repeated somewhere else in the file, without any structure. So how can i add a: Go search for the same numbers you modified in the file (the ten digits followed by ), and modify them the same way.

Thanks for your help

 $file_content = Get-Content "$original_file"
Set-Content -Path "$destination_file" -Value ($file_content -replace "\d(\d{9})(?=<Phone>)", "0`$1")

CodePudding user response:

Here is an example of original file:

1111111111  
AAA BBB 1234567890 BD 1111111111(phone)   
2222222222  
ABC  2222222222 CDK  23456789012 CD 2222222222(phone) 

Since 1111111111 and 2222222222 are followed by (phone), i would like that all their occurences change to 0111111111 and 0222222222.
There will be hundreds of phone numbers their occurences to change

Desired file:

0111111111  
AAA BBB 1234567890 BD 0111111111(phone)   
0222222222  
ABC  0222222222 CDK  23456789012 CD 0222222222(phone) 

CodePudding user response:

I don't see an easier way of doing this, first get all the values that matches "10 digits followed by the word (phone)" and store those matches in a hash table where the keys are the 10 digits that need to be replaced and the values are 0 the 9 remaining digits.

Then we can use the Replace(String, String, MatchEvaluator) method to replace all appearances of the 10 digits matched before (the hash table keys).

$string = @'
1111111111
AAA BBB 1234567890 BD 1111111111(phone)
2222222222
ABC 2222222222 CDK 23456789012 CD 2222222222(phone)
'@

$map = @{}

[regex]::Matches($string, '(?i)(\d(\d{9}))\(phone\)').ForEach({
    $map[$_.Groups[1].Value] = '0'   $_.Groups[2].Value
})

[regex]::Replace($string, ($map.Keys -join '|'), {
    param([string]$matched)
    $map[$matched]
})

Your code should look like this assuming this is what you needed.

Note the use of the -Raw switch is mandatory in this case.

$map = @{}
$content = Get-Content $original_file -Raw

[regex]::Matches($content, '(?i)(\d(\d{9}))\(phone\)').ForEach({
    $map[$_.Groups[1].Value] = '0'   $_.Groups[2].Value
})

$replacedContent = [regex]::Replace($content, ($map.Keys -join '|'), {
    param([string]$matched)
    $map[$matched]
})

Set-Content -Path $destination_file -Value $replacedContent
  •  Tags:  
  • Related