Home > Mobile >  Remove characters from specific positions in text file using powershell
Remove characters from specific positions in text file using powershell

Time:11-15

I have a text file that looks like below.

Domain Certificate
Valid from: Tue Jul 12 05:30:00 IST 2022 
Valid upto: Thu Jan 05 05:29:59 IST 2023
Subject Alternative Names
SAN: yahoo.com
SAN: tw.rd.yahoo.com
SAN: s.yimg.com
SAN: mbp.yimg.com


1st Intermediate Certificate
Valid from: Tue Oct 22 17:30:00 IST 2013 
Valid upto: Sun Oct 22 17:30:00 IST 2028


For each line that contains "Valid from" and "Valid upto", I need to remove characters from specific location and output to be in the format Valid from: Jul 12 2022 or Valid upto: Jan 05 2023

I need to do this across the text file.

Also, if anybody can help modify all lines containing SAN: and help adding quotes in the domain names, like SAN: "yahoo.com"

CodePudding user response:

You can use a switch with the -File parameter to read your file and -Regex to match the lines you want to update, for there you can use the -replace operator with more regex to update those lines:

$newContent = switch -File .\path\to\file.txt -Regex {
    # if the line starts with `SAN`
    '^SAN' { $_ -replace '(?<=: )|$', '"' }
    # if the line starts with `Valid from or Valid upto`
    '^Valid(?: from| upto)' { $_ -replace '(?<=: )\w \s(\w )\s(\d ). \s(\d )', '$1 $2 $3' }
    # else, output the line as-is
    Default { $_ }
}

Then $newContent can be used to save it to a new file:

$newContent | Set-Content path\to\newFile.txt
  • Related