Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

powershell - Matching Lines in a text file based on values in CSV

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	estcsvfile.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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...