您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

具有多行和单行的文本文件中的行数

具有多行和单行的文本文件中的行数

两种情况下的列都不同。为了使其通用,我编写了一个perl脚本来打印行。它从头生成正则表达式,并用它来计算行。我假设第一行始终代表列数。

#!/usr/bin/perl -w

open(FH, $ARGV[0]) or die "Failed to open file";

# Get coloms from HEADER and use it to contruct regex 
my $head = <FH>;
my @col = split(",", $head); # Colums array
my $col_cnt = scalar(@col);  # Colums count

# Read rest of the rows 
my $rows;
while(<FH>) {
$rows .= $_;
}

# Create regex based on number of coloms
# E.g for 3 coloms, regex should be 
# ".*?",".*?",".*?" 
# this represents anything between " and "
my $i=0;
while($i < $col_cnt) {
$col[$i++] = "\".*?\"";
}
my $regex = join(",", @col);

# /s to treat the data as single line 
# /g for global matching
my @row_cnt = $rows =~ m/($regex)/sg; 
print "Row count:" . scalar(@row_cnt);

只需将其存储为row_count.pl并以./row_count.pl filename

其他 2022/1/1 18:43:59 有489人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶