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?
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
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.