Matching Lines in a text file based on values in CSV

ⅰ亾dé卋堺 提交于 2019-12-12 03:56:24

问题


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 } }        

  }


来源:https://stackoverflow.com/questions/42118121/matching-lines-in-a-text-file-based-on-values-in-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!