我有7000多个文本文件,需要检查行/字符串(NAME = ??????)并在csv文件中进行查找以查看是否存在匹配项。如果csv文件中存在匹配项,那么我想将csv中第三列中的内容作为新行添加到原始匹配文本文件中。
原始文本文件中的几行示例:
DATE=23/10/2018 09:10 NAME=CAP9000323 - String / line to find in CSV file USER= SERIAL= BIOS="Mar 20 2009 12:00AM" "LENOVO" "LENOVO - 12e" HWPLATFORM=LENOVO 6258A92 MANUFACTURER=LENOVO CPU=CPU0 2200 Intel(R) Pentium(R) Dual CPU E2200 @ 2.20GHz Model 15, Stepping 13 MEMORY=3652724 NETWORK="7_e1kexpress" "10.248.93.8
CSV文件示例:
Column1,Column2.4,Location NAME=0LJA4Y,10.248.68.50,LOCATION=LEVEL 06 NAME=BTCSHFQLA01,10.91.140.10, NAME=CAO9000961,10.248.146.172,LOCATION=WIRELESS NAME=CAP6040638,10.68.192.151,LOCATION=GRN HO- NAME=CAP9000035,10.248.146.171,LOCATION=WIRELESS NAME=CAP9000066,10.161.240.26,LOCATION=GDNS- NAME=CAP9000077,, NAME=CAP9000323,10.248.93.8,LOCATION=FIRST START- - Match would find this line and copy column 3 content 'LOCATION=FIRST START-' back to original text file that it matched NAME=CAP9000352,, NAME=CAP9001820,10.248.147.0,LOCATION=WIRELESS
预期结果:
DATE=23/10/2018 09:10 NAME=CAP9000323 - String / line to find in CSV file USER= SERIAL= BIOS="Mar 20 2009 12:00AM" "LENOVO" "LENOVO - 12e" HWPLATFORM=LENOVO 6258A92 MANUFACTURER=LENOVO CPU=CPU0 2200 Intel(R) Pentium(R) Dual CPU E2200 @ 2.20GHz Model 15, Stepping 13 MEMORY=3652724 NETWORK="7_e1kexpress" "10.248.93.8 LOCATION=FIRST START- - The content from the CSV file, column 3 added to the original text file
附录:
对不起,我一直在研究(几天),并尝试了各种代码尝试。
这似乎与我所追求的最接近-Matching Lines in a text file based on values in CSV
我最近的尝试是:
$CSVFIL = Import-Csv -Path C:\Collector\MissingLookup.csv
$TEXTFIL = Get-Content -Path "C:\Collector\Jobs\*.txt" | Select-String -Pattern 'NAME='
$matches = @()
foreach ($line in $TEXTFIL) {
if ($CSVFIL -contains $line.COL1) {
$matches += $line.COL3
}
}
if ($matches.Count -gt 0)
{
$matches | Foreach-Object {
Add-Content $TEXTFIL
}
}
我得到的结果是什么都不做或什么也没有写回到原始文本文件。
答案 0 :(得分:0)
我认为这可以做到:
$CSVFIL = Import-Csv -Path 'C:\Collector\MissingLookup.csv'
# get a list of FileInfo objects for all .txt files in the directory and test each of them for the pattern
Get-ChildItem 'C:\Collector\Jobs\*.txt' | ForEach-Object {
$textMatch = $_ | Select-String -Pattern '(NAME=.*)'
# if we have found a file containing the pattern.
if ($textMatch) {
# iterate over the items in the CSV file to see if we can match it with the found string
foreach ($item in $CSVFIL) {
if ($item.Column1 -eq $textMatch.Matches[0].Value) {
# append the value from the 3rd column in the CSV called 'Location'
Add-Content -Path $_.FullName -Value $item.Location
break
}
}
}
}