Tehc
Tehc

Reputation: 689

Filter lines in .txt file with value in PowerShell

Im trying to filter my file in PowerShell so it only contains rows with value. Is there a way to determine if there is a value behind a [CAR] tag?

Or would i have to write something like this?

$file = Get-Content C:\file.txt
foreach ($line in $file){
   if ($line.Length -gt 47){
       #somehow safe those lines in another file
   }
}

Example raw file:

25 13:58:09.680 (0410041011) >>>  DIAG[CAR]
25 13:58:09.788 (0410041120) <<<  [NAK]#99[CAR]0998034398[CAR]0998028069[CAR]
25 13:58:29.789 (0410061120) >>>  DIAG[CAR]
25 13:58:29.896 (0410061227) <<<  [NAK]#99[CAR]0998023613[CAR]
25 13:58:49.897 (0410081228) >>>  DIAG[CAR]
25 13:58:49.981 (0410081311) <<<  [NAK]#99[CAR]0998007552[CAR]0998019114[CAR]0998007115[CAR]
25 13:59:09.982 (0410101312) >>>  DIAG[CAR]
25 13:59:10.069 (0410101399) <<<  [NAK]#99[CAR]0998024143[CAR]
25 13:59:29.070 (0410120400) >>>  DIAG[CAR]
25 13:59:29.177 (0410120507) <<<  [NAK]#99[CAR]

Example of the content which should be in the new file:

25 13:58:09.788 (0410041120) <<<  [NAK]#99[CAR]0998034398[CAR]0998028069[CAR]
25 13:58:29.896 (0410061227) <<<  [NAK]#99[CAR]0998023613[CAR]
25 13:58:49.981 (0410081311) <<<  [NAK]#99[CAR]0998007552[CAR]0998019114[CAR]0998007115[CAR]
25 13:59:10.069 (0410101399) <<<  [NAK]#99[CAR]0998024143[CAR]

Upvotes: 1

Views: 152

Answers (1)

David Brabant
David Brabant

Reputation: 43459

$data = @(
    "25 13:58:09.680 (0410041011) >>>  DIAG[CAR]",
    "25 13:58:09.788 (0410041120) <<<  [NAK]#99[CAR]0998034398[CAR]0998028069[CAR]",
    "25 13:58:29.789 (0410061120) >>>  DIAG[CAR]",
    "25 13:58:29.896 (0410061227) <<<  [NAK]#99[CAR]0998023613[CAR]",
    "25 13:58:49.897 (0410081228) >>>  DIAG[CAR]",
    "25 13:58:49.981 (0410081311) <<<  [NAK]#99[CAR]0998007552[CAR]0998019114[CAR]0998007115[CAR]",
    "25 13:59:09.982 (0410101312) >>>  DIAG[CAR]",
    "25 13:59:10.069 (0410101399) <<<  [NAK]#99[CAR]0998024143[CAR]",
    "25 13:59:29.070 (0410120400) >>>  DIAG[CAR]",
    "25 13:59:29.177 (0410120507) <<<  [NAK]#99[CAR]"
)

# Use lookahead for a digit
$data -match "\[CAR\](?=\d)"

Upvotes: 1

Related Questions