user2637664
user2637664

Reputation: 43

RegEx command to get date

Using the following RegEx line in my PowerShell script to pull dates from .txt files. The script is reading and pulling the dates to a .csv file in this format Year,Month,Day,Hour,Min,Sec (2020,06,20,00,50,56). I'm looking for some guidance on how I can get the date just to show without the commas in this format 2020-06-20

This is how date is listed in .txt files see line that starts with Generated:

Node 001 Status Report - Report Version 20200505;
Generated 2020-06-20 00:50:56;

Below is portion of the script that's reading and pulling the date:

If($_ -imatch 'Generated'){       
   $Date = ([regex]::Matches($_,'\b\d+') | select value).value -join ','
}

Upvotes: 1

Views: 330

Answers (2)

AdminOfThings
AdminOfThings

Reputation: 25001

You can use Select-String to read each file line by line and pattern match against each line:

Select-String -Path a.txt,b.txt -Pattern '^Generated (\d{4}-\d{2}-\d{2})' |
    Foreach-Object { $_.Matches.Groups[1].Value }

Select-String also adds other benefits. Each pattern match is a MatchInfo object that contains the file name, line number that matched, and the line that contains the match. The -AllMatches switch will match as many times as possible per input line. The -Path parameter accepts an array of files and/or wildcards in the path. The [1] index is the first unnamed capture group results, which will be what matches within the first set of ().


As an aside, I would verify that the ####-##-## is actually a valid date unless you know that will always be so within your data. You can do this easily if your system culture settings allow for the date format:

Select-String -Path a.txt,b.txt -Pattern '^Generated (\d{4}-\d{2}-\d{2})' | Foreach-Object {
    $_.Matches.Groups[1].Value | Where { $_ -as [datetime] }
}

If the culture settings do not allow the format, you will need to use ParseExact or TryParseExact to test the date.


If you must work within your current data format, then you can do the following to extract the date from the comma-delimited string in the required format:

If($_ -imatch 'Generated'){       
   $Numbers = ([regex]::Matches($_,'\b\d+') | select value).value -join ','
   $Date = ($Numbers -split ',')[0..2] -join '-'
}

Upvotes: 1

Nico Nekoru
Nico Nekoru

Reputation: 3102

You are joining the expression with -join ',' for commas, if you want dashes instead, just change that to a dash.

If($_ -imatch 'Generated'){       
   $Date = ([regex]::Matches($_,'\b\d+') | select value).value -join '-'
}

Upvotes: 0

Related Questions