![](/img/trans.png)
[英]How to calculate and used memory of multiple instance of a single process using powershell?
[英]process multiple CSV file and delete rows in a single column which has double semi colon characters using powershell
考慮我有一個下面的 CSV 文件。
輸入:
ID;ITEM_ID;STATUS;
001;;RELEASED;
002;36530;RELEASED;
003;86246;RELEASED;
004;;RELEASED;
我想刪除具有的行;; (ITEM_ID)丟失並保存它。我嘗試在一個示例文件上執行此操作,它按預期工作。
Import-Csv -Path ".\TestFile.CSV" | where {$_.ITEM_ID -ne ""} | Export-Csv -Path ".\TestFile-temp.CSV" -NoTypeInformation
Remove-Item -Path '.\TestDir\TestFile.csv'
Rename-Item -Path '.\TestDir\TestFile-temp.csv' -NewName 'TestFile.csv'
output:
ID;ITEM_ID;STATUS;
002;36530;RELEASED;
003;86246;RELEASED;
挑戰是,我有多個 csv 文件,它在不同的列中沒有價值,但是當我在 excel 文件中打開時,它在單個列中。 所以它不采用條件 < where {$_.ITEM_ID -ne ""} >。 現在我必須搜索/解析每個 csv 文件的每一行,在該行中搜索特殊字符 (;;) 並刪除該行並保存文件。
我擅長 shell 腳本,但是我對 powershell 腳本非常陌生。 誰能幫我在這里獲取邏輯或使用其他可以完成這項工作的cmdlet?
$fileDirectory = "C:\Users\Administrator\Documents\check";
foreach($file in Get-ChildItem $fileDirectory)
{
$csvFileToCheck = Import-Csv -Path $fileDirectory\$file
$noDoubleSemiComma = foreach($line in $csvFileToCheck)
{
if(Select-String << i want the logic here>>)
{
$line
}
}
$noDoubleSemiComma | Export-Csv -Path $fileDirectory\tmp.csv -NoTypeInformation
Remove-Item -Path $fileDirectory\$file
Rename-Item -Path $fileDirectory\tmp.csv -NewName $file
}
如評論所述,您需要添加參數-Delimiter ';'
到 cmdlet,否則使用逗號解析 CSV 中的字段。
據我了解,您還想刪除所有字段和標題周圍的引號Export-Csv
輸出,對於 PowerShell 版本 7,您可以選擇使用參數-UseQuotes AsNeeded
。
由於這不適用於 5.1 版,我前段時間制作了 function ConvertTo-CsvNoQuotes以安全地刪除引號。 (簡單地用空字符串替換它們是危險的,因為有時值確實需要引號)
將 function 復制到頂部的腳本中,然后在其下方,您的代碼可以簡化如下:
$fileDirectory = "C:\Users\Administrator\Documents\check"
Get-ChildItem -Path $fileDirectory -Filter '*.csv' -File | ForEach-Object {
# for better readability store the full path of the file in a variable
$filePath = $_.FullName
(Import-Csv -Path $filePath -Delimiter ';') | ConvertTo-CsvNoQuotes -Delimiter ';' | Set-Content $filePath -Force
Write-Host "File '$filePath' modified"
}
在所有有用的建議之后,我終於確定了它。 因為我的 power-shell 版本是 5.1,所以我不得不在 export-csv 之后使用邏輯來修剪雙引號。 Powershell 版本 7 及更高版本具有-UseQuotes
也可以解決該問題。 希望這對其他人有幫助。
$fileDirectory = "C:\Users\Administrator\Documents\check";
foreach($file in Get-ChildItem $fileDirectory)
{
Import-Csv -Path $fileDirectory\$file -Delimiter ';' | where {$_..ITEM_ID -ne ""} | Export-Csv -Path $fileDirectory\temp.csv -Delimiter ';' -NoTypeInformation
$Test = Get-Content $fileDirectory\temp.csv
$Test.Replace('";"',";").TrimStart('"').TrimEnd('"') | Out-File $fileDirectory\temp.csv -Force -Confirm:$false
Remove-Item -Path $fileDirectory\$file
Rename-Item -Path $fileDirectory\temp.csv -NewName $file
Write-Output "$file file modified."
}
歡迎任何減少代碼行數的建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.