Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations dencom on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stumped by -Replace with RegEx 1

Status
Not open for further replies.

markdmac

MIS
Dec 20, 2003
12,340
US
I have some files with lines of text that will include a date int eh format of Mar 1, 2015. I need to replace any dates with the format of 3/1/2015. I can correctly identify the date with a regular expression, just not sure how I can use a -Replace to change the format. Can anyone assist?

Code:
$WordDate = "(?<month>[\dA-Za-z]+) (?<day>\d{1,2}), (?<year>\d{2,4})"
$Line = "4I0139L4               Mar 1, 2015 12:18:58 AM               1 Years"
 
I am able to replace with the current date, but I need to identify the date that is already in the line that was matched with the regular expression. Any help would be appreciated.
 
Well, I finally got it. There may be a more efficient way to do this and I would be grateful for any suggestions. This does all I needed though. Removed all time strings and replaces dates listed as Month Day, Year as MM/dd/yyyy format then writes the data back to the file.

Code:
$FTPContent = (Get-Content C:\Temp\OpsCenter_4I-FTP_23_02_2015_07_00_12_998_AM_12.TSV) 
$WordDate = "(?<month>[\dA-Za-z]+) (?<day>\d{1,2}), (?<year>\d{2,4})"
$TimeRegex = "(1[012]|0?\d):[0-5]?\d(:[0-5]?\d)?\s+[AaPp][Mm]?"
Foreach ($Line in $FTPContent)
{
    $Date = $Line | % {$_ -match $WordDate > $null; $matches[0]}
    $a = Get-Date($Date)
    $a.ToString('MM-dd-yyyy') > $null
    $NewLine = $Line -replace $WordDate, $a
    $NewLine2 = $NewLine -Replace "00:00:00",""
    $NewLine3 = $NewLine2 -Replace $TimeRegex,""
    $NewLine3
    $Report = $Report + $NewLine3 + "`r`n"
}
Set-Content C:\Temp\OpsCenter_4I-FTP_23_02_2015_07_00_12_998_AM_12.TSV $Report

I hope that helps.

Regards,

Mark

No trees were harmed in posting this message, however a significant number of electrons were terribly inconvenienced.

Check out my scripting solutions at
Work SMARTER not HARDER.
 
Thanks for sharing this.

"But thanks be to God, which giveth us the victory through our Lord Jesus Christ." 1 Corinthians 15:57
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top