Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Extract datetime from a string (11/11/2020 11:23:45 Text2 12345) without using Regex

Tags:

powershell

I have a text file

11/11/2020 11:23:45 Text2 12345

Text 2020-11-25 11:23:46 12345

I am looping through the text file and I need output for line 1 as 11/11/2020 11:23:45 by specifying date format as "MM/dd/yyyy HH:mm:ss" and for line 2 as 2020-11-25 11:23:46 by specifying date format as "yyyy-dd-MM HH:mm:ss"

$pattern = "MM/dd/yyyy HH:mm:ss"
$dateString = 11/11/2020 11:23:45 Text2 12345
$date = [datetime]::ParseExact($dateString,$date_format,$null)

I cannot use regex as there might be quite few number of date formats in the text file and parseExact is not working as the string has other values combined with Date.

Any help please!!

like image 458
Dhatri Maddipati Avatar asked Feb 03 '26 10:02

Dhatri Maddipati


1 Answers

I suggest using a switch statement with the -File and -Regex parameters:

# Sample input file.
$file = './sample.txt'

# Add sample data to the file.
@'
11/11/2020 11:23:45 Text2 12345
Text 2020-11-25 11:23:46 12345
'@ > $file

# Read the file line by line, and perform regex matching on each.
# Convert each match to a [datetime] instance by casting and output it.
switch -Regex -file $file {
  '\b\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}\b' { # MM/dd/yyyy HH:mm:ss
    [datetime] $Matches[0]
  }
  '\b\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b' { # yyyy-dd-MM HH:mm:ss
    [datetime] $Matches[0] 
  }
}

Note that both formats in the sample lines can directly be cast to [datetime]. If there are additional formats that cannot, perform the ::ParseExact() call in the respective branch handlers.

The above yields (on my en-US system):

Wednesday, November 11, 2020 11:23:45 AM
Wednesday, November 25, 2020 11:23:46 AM
like image 164
mklement0 Avatar answered Feb 06 '26 02:02

mklement0