Matching Lines in a text file based on values in C

2019-09-12 03:23发布

问题:

Hi Everyone,

I am having trouble with the below script. Here is the requirement:

1) Each text file needs to be compared with a single CSV file. The CSV file contains the data to that if present in the text file should match.

2) If the data in the text file matches, output the matches only and run jobs etc..

3) If the text file has no matches to the CSV file, exit with 0 as no matches are found.

I have tried to do this, but what I end up with is matches, and also non matches. What I really need is to match the lines, run the jobs,exit, if text file has no matches, then return 0

$CSVFIL = Import-Csv -Path $DRIVE\test\csvfile.csv
$TEXTFIL = Get-Content -Path "$TEXTFILFOL\*.txt" |
  Select-String -Pattern 'PAT1' | 
    Select-String -Pattern 'PAT2' | 
      Select-String -Pattern 'TEST'

ForEach ($line in $CSVFIL) {

If ($TEXTFIL -match $line.COL1)  {

Write-Host 'RUNNING:' ($line.JOB01)

} else {

write-host "No Matches Found Exiting"

回答1:

I would handle this a different way. First you need to find matches, if there are matches then process else output 0.

$matches = @()

foreach ($line in $CSVFIL)
{
    if ($TEXTFIL -contains $line.COL1)
    { $matches += $line }
}

if ($matches.Count -gt 0)
{
    $matches | Foreach-Object {
        Write-Output "Running: $($_.JOB01)"
    }
}
else
{
    Write-Output "No matches found, exiting"
}


回答2:

$CSVFIL = Import-Csv -Path "$DRIVE\test\csvfile.csv"
Get-Content -Path "$TEXTFILFOL\*.txt" |
where {$_ -like "*PAT1*" -and $_ -like "*PAT2*" -and $_ -like "*TEST*" } |
  %{
  $TEXTFOUNDED=$_; $CSVFIL | where {$TEXTFOUNDED -match $_.COL1} | 
     %{    [pscustomobject]@{Job=$_.JOB01;TextFounded=$TEXTFOUNDED;Col=$_.COL1 } }        

  }