Home > Net >  PowerShell v5.1: problem with replacing text in a file using regex patterns
PowerShell v5.1: problem with replacing text in a file using regex patterns

Time:04-22

I tried to follow answers provided here and here.

In a "test1.txt" file I have these contents:

20220421
20220422
20220423
20220424:
222

I want to replace the contents so that they would look like this in the output file "test2.txt":

20220421:
20220422:
20220423:
20220424:
222

I attempted to achieve this with the following code:

(Get-Content '.\test1.txt').replace('^\d{8}$', '^\d{8}:$') | Out-File '.\test2.txt'

However, instead of the expected results, I got the following content in "test2.txt":

20220421
20220422
20220423
20220424:
222

Can someone explain why I'm not achieving the expected results?

CodePudding user response:

You are not using the regex supporting -replace operator and you are usinv a regex in the replacement instead of the correct replacement pattern.

You can use

(Get-Content '.\test1.txt') -replace '^(\d{8}):?\r?$', '$1:') | Out-File '.\test2.txt'

The ^(\d{8}):?\r?$ regex matches eight digits capturing them into Group 1, and then an optional colon, an optional CR and then asserts the end of string position.

The replacement is Group 1 value ($1) plus the colon char.

CodePudding user response:

Powershell is treating $ and ^ as the beginning and end of the whole contents, not individual lines.

This is not quite what you want - I can't get the line break in the replacement string.

@" 20220421 20220422 20220423 20220424: 222 "@ -replace "(\d{8})\n",'$1:'

line breaks not working

  • Related