簡體   English   中英

使用 Powershell,我如何導出和刪除 csv 行,其中特定值*未在 *不同* csv 中找到*?

[英]Using Powershell, how can I export and delete csv rows, where a particular value is *not found* in a *different* csv?

我有兩個文件。 一種叫allper.csv

institutiongroup,studentid,iscomplete
institutionId=22343,123,FALSE
institutionId=22343,456,FALSE
institutionId=22343,789,FALSE

另一種叫做actswithpersons.csv

abc,123;456
def,456
ghi,123
jkl,123;456

注意:actswithpersons.csv 沒有標題 - 它們將在稍后通過 excel 電源查詢添加,所以現在不希望它們在那里。 actwithpersons csv 列用逗號分隔 - 只有兩列,第二列包含多個 personids - Excel 稍后將處理這個問題。

我想從 allper.csv 中刪除所有行,其中 personid 沒有出現在actswithpersons.csv 中,並將它們導出到另一個 csv。 所以在期望的結果中, allper.csv 看起來像這樣

institutiongroup,studentid,iscomplete
institutionId=22343,123,FALSE
institutionId=22343,456,FALSE

和 export.csv 看起來像這樣

institutiongroup,studentid,iscomplete
institutionId=22343,789,FALSE

我已經得到了以下內容,它將放入 shell 是否在 actwithpersons.csv 文件中找到 personid。

$donestuff = (Get-Content .\ActsWithpersons.csv | ConvertFrom-Csv); $ids=(Import-Csv .\allper.csv);foreach($id in $ids.personid) {echo $id;if($donestuff -like "*$id*" )
{
   echo 'Contains String'
}
else
{
   echo 'Does not contain String'
}}

但是,我不確定如何 go 最后一步,並從 allper.csv 中導出並刪除不需要的行

我試過(在很多事情中)

$donestuff = (Get-Content .\ActsWithpersons.csv | ConvertFrom-Csv);
Import-Csv .\allper.csv |
    Where-Object {$donestuff -notlike $_.personid} |
        Export-Csv -Path export.csv -NoTypeInformation

這花了很長時間,給我留下了一個空的 csv。 所以,如果你能提供任何指導,請幫助。

由於您的actwithpersons.csv沒有標題,為了讓您導入為 csv,您可以在Import-CsvConvertFrom-Csv中指定-Header參數; 以前的 cmdlet 是更好的解決方案。

話雖如此,您可以對這 2 列使用任何 header 名稱,然后在使用Where-Object導入allper.csv后按給定的列名稱(在本例中為 ID )進行過濾:

$awp = (Import-Csv -Path '.\actswithpersons.csv' -Header 'blah','ID').ID.Split(';')
Import-Csv -Path '.\allper.csv' | Where-Object -Property 'Studentid' -notin $awp

這應該給你:

institutiongroup    studentid iscomplete
----------------    --------- ----------
institutionId=22343 789       FALSE    

如果你想用Get-Content來做,你可以用,;的分隔符來分割。 . 這應該只為您提供一行值,然后您可以使用與上面相同的過濾器比較整個變量( $awp ),這將為您提供相同的結果:

$awp = (Get-Content -Path '.\actswithpersons.csv') -split ",|;" 
Import-Csv -Path '.\allper.csv' | Where-Object -Property 'Studentid' -notin $awp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM