Like 用户1146332,我也建议改用更强大的语言。这里有一个使用的例子perl /questions/tagged/perl。它使用模块Getopt::Long
读取参数并循环文件以查找匹配行。
它似乎有效,但需要您更好地检查错误,例如,book
and author
变量在正则表达式中使用之前定义。
还有一件事,我用split()
用冒号来提取字段,我不知道如何处理名称中带有冒号的书,但在这种情况下,您将需要一个额外的模块来解析 CSV,例如Text::CSV
或者与更好的人更加努力地战斗split
表达。
#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long;
my ($book, $author, $newbook, $quantity);
my $r = GetOptions(
q|book=s| => \$book,
q|author=s| => \$author,
q|newbook=s| => \$newbook,
q|quantity=i| => \$quantity,
) or die;
open my $fh, '<', $ARGV[0] or die;
while ( <$fh> ) {
chomp;
my @f = split /:/;
next if @f < 5;
if ( $f[0] =~ m/(?i)\Q$book\E/ &&
$f[1] =~ m/(?i)\Q$author\E/ ) {
$f[0] = defined $newbook ? $newbook : $f[0];
$f[3] = defined $quantity ? $quantity : $f[3];
printf qq|%s\n|, join q|:|, @f;
next;
}
printf qq|%s\n|, $_;
}
一个例子:
perl script.pl --book="lord of the ring" --author=dep --newbook="Lord of the King" --quantity=99 infile
Yields:
Harry Potter - The Half Blood Prince:J.K Rowling:40.30:10:50
The little Red Riding Hood:Dan Lin:40.80:20:10
Harry Potter - The Phoniex:J.K Rowling:50.00:30:20
Harry Potter - The Deathly Hollow:Dan Lin:55.00:33:790
Little Prince:The Prince:15.00:188:9
Lord of the King:Johnny Dept:56.80:99:38
Three Little Pig:Andrew Lim:89.10:290:189
All About Ubuntu:Ubuntu Team:76.00:55:133
Catch Me If You Can:Mary Ann:23.60:6:2
Happy Day:Mary Ann:12.99:197:101
haha:gaga:1:10:1