Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing a Matched Character in Powershell

I have a text file of 3 name entries:

# dot_test.txt
001 AALTON, Alan .....25 Every Street
006 JOHNS, Jason .... 3 Steep Street
002 BROWN. James .... 101 Browns Road

My task is to find instances of NAME. when it should be NAME, using the following:

Select-String -AllMatches -Path $input_path -Pattern '(?s)[A-Z]{3}.*?\D(?=\s|$)' -CaseSensitive |
    ForEach-Object { if($_.Matches.Value -match '\.$'){$_.Matches.Value -replace '\,$'} }

The output is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

BROWN.

The conclusion is this script block identifies the instance of NAME. but fails to make the replacement.

Any suggestions on how to achieve this would be appreciated.

>Solution :

$_.Matches.Value -replace '\,$'

This attempts to replace a , (which you needn’t escape as \,) at the end of ($) your match with the empty string (due to the absence of a second, replacement operand), i.e. it would effectively remove a trailing ,.

However, given that your match contains no , and that you instead want to replace its trailing . with ,, use the following:

$_.Matches.Value -replace '\.$', ','  # -> 'BROWN,'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading