我嘗試替換 csv 中的一些文本,如下所示:
$csv = Import-Csv $csvFileName -Delimiter ';'
foreach ($line in $csv)
{
$properties = $line | Get-Member -MemberType Properties
for ($i = 0; $i -lt $properties.Count;$i )
{
$column = $properties[$i]
$value = $line | Select -ExpandProperty $column.Name
# Convert numbers with , as separator to . separator
if ($value -match "^[ -]?(\d*\,)?\d $")
{
$value = $value -replace ",", "."
# HOW TO update the CSV cell with the new value here???
# ???
}
}
}
$csv | Export-Csv $csvFileName -Delimiter ',' -NoTypeInformation -Encoding UTF8
如您所見,我錯過了要使用新值更新 csv 行的單元格值的行=> 有人可以告訴我該怎么做嗎?
uj5u.com熱心網友回復:
假設您使用的正則運算式將與您期望的模式匹配,您可以使用 2 個foreach回圈來簡化代碼,這比for. 此方法呼叫可用于所有 PowerShell 物件的內部PSObject成員。
$csv = Import-Csv $csvFileName -Delimiter ';'
foreach ($line in $csv) {
foreach($property in $line.PSObject.Properties) {
if ($property.Value -match "^[ -]?(\d*\,)?\d $") {
# regex operator not needed in this case
$property.Value = $property.Value.Replace(",", ".")
}
}
}
$csv | Export-Csv ....
您還可以在管道中執行所有程序(上面的方法應該明顯更快,但是這種方法可能對記憶體更友好):
Import-Csv $csvFileName -Delimiter ';' | ForEach-Object {
foreach($property in $_.PSObject.Properties) {
if ($property.Value -match "^[ -]?(\d*\,)?\d $") {
# regex operator not needed in this case
$property.Value = $property.Value.Replace(",", ".")
}
}
$_ # => output this object
} | Export-Csv myexport.csv -NoTypeInformation
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464783.html
上一篇:如何查找具有最新訊息的群組?
下一篇:從python使用命令提示符
