我有一个.csv文件,我想在其中查找特定字词' ELECTRICIANS'这是该列的第一个条目。我想用名字ELECTRICIANS打印整个列,如果我用其他任何一个词,我应该打印一个错误。
我按如下方式执行了grep操作:
my $exit = system("grep -q $column_name $file_name");
if ($exit == 0)
{
print "Entered column name $column_name found in file $file_name\n";
}
else {
print "Column name not found, try again!\n";
exit;
}
现在如何在' ELECTRICIANS'
下打印文件内的列?.csv文件的内容如下:
WEEK,SITE ENGINEERS,SITE ENGINEERS 2,ELECTRICIANS,ELECTRICIANS 2
ONE,13,28,17,29
TWO,13,30,18,27
THREE,13,30,14,23
FOUR,15,30,12,29
FIVE,15,22,16,24
SIX,16,30,20,30
SEVEN,12,27,13,29
EIGHT,19,22,16,29
NINE,19,21,19,30
TEN,12,22,14,30,13
答案 0 :(得分:1)
示例数据的最后一行似乎有一个额外的列。
但这可以做你想要的。
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
# read header
my @cols = split /,/, <DATA>;
# Process the rest of the data
while (<DATA>) {
my %data;
@data{@cols} = split /,/;
say $data{ELECTRICIANS};
}
__DATA__
WEEK,SITE ENGINEERS,SITE ENGINEERS 2,ELECTRICIANS,ELECTRICIANS 2
ONE,13,28,17,29
TWO,13,30,18,27
THREE,13,30,14,23
FOUR,15,30,12,29
FIVE,15,22,16,24
SIX,16,30,20,30
SEVEN,12,27,13,29
EIGHT,19,22,16,29
NINE,19,21,19,30
TEN,12,22,14,30,13
答案 1 :(得分:0)
您正在编写一个Perl脚本,不需要将子进程生成到shell,然后调用其他一些shell函数。 Perl内置了grep。下面举例说明如何在Perl中完全实现相同的结果。我还提供了解释脚本的评论。
use strict;
use warnings;
#set the column name, this could be changed to accept input from user,
#also read from the data file handle, this could also be changed to read from any other file
my $column = "ELECTRICIANS";
my @headers = split(',',<DATA>);
#Check for the column name rom the headers just read from the file handle, if not found then exit
unless (grep {$_ eq "$column"} @headers){
print "Column name $column not found, try again!\n";
exit 1;
}
print $column, "\n";
#if we got to hear then the CSV file must have the column we are insterested in so start looping though the lines
#split each line into fields then for each lin make a hash using the headers and the fields. then we can print the column
#we are interested in
while(<DATA>){
chomp();
my @fields = split(',');
my %data;
@data{@headers}=@fields;
print $data{$column}, "\n";
}
__DATA__
WEEK,SITE ENGINEERS,SITE ENGINEERS 2,ELECTRICIANS,ELECTRICIANS 2
ONE,13,28,17,29
TWO,13,30,18,27
THREE,13,30,14,23
FOUR,15,30,12,29
FIVE,15,22,16,24
SIX,16,30,20,30
SEVEN,12,27,13,29
EIGHT,19,22,16,29
NINE,19,21,19,30
TEN,12,22,14,30,13
这会产生输出
ELECTRICIANS
17
18
14
12
16
20
13
16
19
14
当读取每一行并将其放入哈希时,您还可以打印其他列,因为您知道每个字段的列名称。
答案 2 :(得分:0)
我常常因为我的单行而受到批评,但这里只有一个:
perl -F, -slane '
if ($. == 1) {
for ($i=0; $i<@F; $i++) {
if ($F[$i] eq $colname) {
$colno = $i;
last;
}
}
die "cannot find $colname column" unless defined $colno;
}
print $F[$colno]
' -- -colname=ELECTRICIANS file.csv