在perl中逐行打印出csv

时间:2018-08-07 21:03:35

标签: bash perl

我有一个值列表

2018.04.09, 22:39, SPX , 2200 , 10 
2018.04.09, 22:39, SPX , 2225 , 5 
2018.04.09, 22:39, SPX , 2175 , 5
2018.04.26, 34:03, SPXW , 2585 , 66
2018.04.26, 34:03, SPXW , 2595 , 33
2018.04.26, 34:03, SPXW , 2575 , 33
2018.04.26, 34:03, SPXW , 2580 , 33
2018.04.26, 34:03, SPXW , 2600 , 33
2018.04.26, 34:03, SPXW , 2590 , 66

我需要花些时间在这些值上-只需替换一下vlaues。

2018.04.09 where ticker = `SPX, strikeprice = 2200, orderqty = 10, (string transacttime) like "*22:39.*"
2018.04.09 where ticker = `SPX, strikeprice = 2225, orderqty = 5, (string transacttime) like "*22:39.*" 
2018.04.09 where ticker = `SPX, strikeprice = 2200, orderqty = 5, (string transacttime) like "*22:39.*"  

我不知道该如何在bash中使用perl进行操作。如何在Perl中做到这一点?

#!/bin/bash
OLDIFS=$IFS
IFS=,
while read -r date time sym str qty
do
echo "
$date where ticker = \`${sym}, strikeprice = ${str}, orderqty = ${qty}, (string transacttime) like \"*${time}*\"
"
done < /tmp/list
IFS=$OLDIFS

3 个答案:

答案 0 :(得分:2)

请参见split

#!/usr/bin/perl
use warnings;
use strict;

open my $in, '<', '/tmp/list' or die $!;
while (<$in>) {
    chomp;
    my ($date, $time, $sym, $str, $qty) = split /,/;
    print qq(\n$date where ticker = `$sym, strikeprice = $str, orderqty = $qty, (string transacttime) like "*$time*"\n\n);
}

如果您不想在每行周围都留空行,只需从带引号的字符串的开头和结尾删除\n

答案 1 :(得分:1)

Text::CSV的基本用法:

use strict;
use warnings;

use Text::CSV;
my $parser = Text::CSV->new;

open my $data, '<', 'data.csv';
while (my $row = $parser->getline($data)) {
    # $row is an array reference. dereference by using "@$row"
    print 'the row is: '.join('||', @$row)."\n";
    # or access elements like $row->[0]
    print 'the first element of the row is '.$row->[0];
}

答案 2 :(得分:1)

Parse :: CSV也具有非常好的界面。

# Simple headerless comma-seperated column parser
my $simple = Parse::CSV->new(
    file => 'file.csv',
);

while ( my $array_ref = $simple->fetch ) {
   # Do something...
}