Powershell在csv中查找和替换单元格值

时间:2021-06-14 19:24:55

标签: powershell csv

我正在尝试解析 csv 文件中名为 price 的列。

csv price column

在此列中,我需要找到其中包含“-”的值。在上面的示例中,您可以看到有两种情况(132-24.5 和 158-25)。然后我需要使用以下公式替换 csv 文件中的该值:

(破折号左边的数字+破折号右边的数字/32)

所以 132-24.5 将是 132+24.5/32 = 132.765625

我已经在 matlab 中编写并使用了一年的代码,但我需要将其转换为 PowerShell,而且我对 powershell 的工作方式非常迷茫。请指导我。

Matlab 代码如下:

[~,~,data] = xlsread(['C:\Users\Me' filelist(3,:)]);

for x = 2:length(data(:,4))
bondfind = strfind(num2str(cell2mat(data(x,4))),'-');
 if ~isempty(bondfind)
    priceString = num2str(cell2mat(data(x,4)));
    price = str2num(priceString(1:bondfind-1)) + str2num(priceString(bondfind+1:end))/32;
    data(x,4) = num2cell(price);
 end
end

xlswrite(['C:\Users\Me\' filelist(3,:)],data);

1 个答案:

答案 0 :(得分:1)

所以,如果您的文件看起来像这样:

Article,Price
Something,132-24.5
Stuff,1371.8
More Stuff,587.3
Another thing, 158-25

您可以这样做以对列 Price 中的值进行转换:

$data = Import-Csv -Path 'D:\Test\TheFile.csv'
foreach ($item in $data) {
    if ($item.Price -match '-') {
        $left, $right = [double[]]($item.Price -split '-')
        $item.Price = $left + $right / 32
    }
}

# output on screen
$data

# save as (new) CSV file
$data | Export-Csv -Path 'D:\Test\TheNewFile.csv' -NoTypeInformation

屏幕输出:

Article            Price
-------            -----
Something     132.765625
Stuff             1371.8
More Stuff         587.3
Another thing  158.78125
相关问题