简体   繁体   English

如何在Perl中对CSV文件的一列运行操作?

[英]How can run an operation on one column of an CSV file in Perl?

I need to parse and convert an entire column in a simple CSV file that has two columns. 我需要在具有两列的简单CSV文件中解析并转换整个列。

John, 128222971326628000
Paul, 128491909317205000
Greg, 128160037933161000

Basically I need to perform some arithmetic on the second column and update the value in the column with the result of this operation while leaving the first column untouched. 基本上,我需要对第二列执行一些算术运算,并使用此操作的结果更新该列中的值,同时保持第一列不变。

Can you please give me some hints on how would I go about doing this? 您能给我一些提示,我该怎么做吗?

I have looked at some examples and none of them explains how to update an entire column. 我看了一些示例,但没有一个示例说明如何更新整个专栏。

Thank you in advance for your help. 预先感谢您的帮助。

It sounds like you need Tie::File : 听起来您需要Tie::File

#!/usr/bin/perl

use strict;
use warnings;

use Tie::File;

my $filename = shift; #get filename from commandline

tie my @records, "Tie::File", $filename
    or die "could not open $filename: $!";

for my $record (@records) {
    my @rec = split /, /, $record;
    $rec[1] /= 2; #reduce the second column by half
    #prevent perl from using scientific notation
    $rec[1] = sprintf "%18.0f", $rec[1]; 
    $record = join ", ", @rec;
}

In addition to the answers you have already, I would note that the size of the numbers could pose a problem for you: you might lose some precision when you try to perform math (that's what happened on my system when I ran the answer by Chas. Owens, for example). 除了已经有的答案外,我还会注意到数字的大小可能还会给您带来问题:尝试执行数学运算时,您可能会失去一些精度(这是我在Chas中运行答案时系统上发生的情况)以欧文斯为例) If that's a problem on your system, you can look into Perl's modules for working with large numbers: Math::Big , Math::BigInt , etc. 如果这是您系统上的问题,则可以研究Perl的用于处理大量数字的模块: Math :: BigMath :: BigInt等。

It sort of depends on the arithmetic you want to do, but you might be able to get away with something like this. 它在某种程度上取决于您要执行的算术运算,但是您也许可以摆脱类似的情况。 Here's a command line example that adds 1 to every number in the second column of the file. 这是一个命令行示例,在文件第二列的每个数字上加1。

perl -a -n -i -e '$F[1]++;print "$_ " for @F;print "\n"' csv_file

Note though that this is splitting on the space in your example, rather than on the ','. 请注意,尽管这是在示例中的空格上分开的,而不是在','上。

  1. Use Text::CSV to extract the data (for complex CSV files) http://metacpan.org/pod/Text::CSV 使用Text :: CSV提取数据(用于复杂的CSV文件) http://metacpan.org/pod/Text::CSV

2.Do whatever you need to do. 2.做任何你需要做的。

  1. Write it back to file 写回文件

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM