簡體   English   中英

如何在Perl中對CSV文件的一列運行操作?

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

我需要在具有兩列的簡單CSV文件中解析並轉換整個列。

John, 128222971326628000
Paul, 128491909317205000
Greg, 128160037933161000

基本上,我需要對第二列執行一些算術運算,並使用此操作的結果更新該列中的值,同時保持第一列不變。

您能給我一些提示,我該怎么做嗎?

我看了一些示例,但沒有一個示例說明如何更新整個專欄。

預先感謝您的幫助。

聽起來您需要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;
}

除了已經有的答案外,我還會注意到數字的大小可能還會給您帶來問題:嘗試執行數學運算時,您可能會失去一些精度(這是我在Chas中運行答案時系統上發生的情況)以歐文斯為例) 如果這是您系統上的問題,則可以研究Perl的用於處理大量數字的模塊: Math :: BigMath :: BigInt等。

它在某種程度上取決於您要執行的算術運算,但是您也許可以擺脫類似的情況。 這是一個命令行示例,在文件第二列的每個數字上加1。

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

請注意,盡管這是在示例中的空格上分開的,而不是在','上。

  1. 使用Text :: CSV提取數據(用於復雜的CSV文件) http://metacpan.org/pod/Text::CSV

2.做任何你需要做的。

  1. 寫回文件

希望這可以幫助

暫無
暫無

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

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