Home > Enterprise >  Match Regex from File - PowerShell
Match Regex from File - PowerShell

Time:10-13

I am trying to set up a PowerShell script to change the date within a file whenever it is run. Below is the current code. It looks for regex with an existing date to replace. I don't know if my regex is correct, but it should check for a date in the format of MM.dd.yy i.e. 10.12.22 for October 12, 2022.

$regexDate = '^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$'
$currentDate = Get-Date -UFormat "%m.%d.%y"

Get-Content -path "template1.dat" | % { $_ -Replace $regexDate, $currentDate } |  Out-File "template1.dat"

Example input file:

Date: 10.12.22

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Quam adipiscing vitae proin sagittis nisl rhoncus. 

Placerat orci nulla pellentesque dignissim enim sit amet venenatis.

CodePudding user response:

The date format in your file is with 2 digits at the end for the year, instead of 4 digits (also not at the start of the string with the ^ anchor)

\b(?:0?[1-9]|1[012])\.(?:0?[1-9]|[12][0-9]|3[01])\.\d\d\b

Or change the \b at the end to $ for the end of the string.

Regex demo

CodePudding user response:

Without regex, what about this ?

$pathtofile = "Path to file"
$contenttokeep = Get-Content -LiteralPath $pathtofile | Select-Object -Skip 1

(Get-Date -UFormat "%m.%d.%y") | Out-File -LiteralPath $pathtofile
$contenttokeep | Out-File -LiteralPath $pathtofile -Append
  • Related