While you can do this sort of thing by wrapping the more primitive Unix tools — grep
, sed
, awk
, etc. — in a shell script, this sort of problem really wants to be handled in a full programming language that has a powerful regular expression system. Personally, I'd reach for Perl:
#!/usr/bin/perl -w
use strict;
my $line = 0;
my ($junk, $color, $number);
open my $data, '<', 'data.txt' or die "open: $!\n";
while (<$data>) {
chomp;
++$line;
if (m/Land/) {
print "color=L, number=0\n";
}
else {
($junk, $color, $number) = m/, (\d+)?([WURBG]+) \((\d+)\)$/;
if (defined $color and defined $number) {
$color = 'M' if length($color) > 1;
print "color=$color, number=$number\n";
}
else {
($junk, $number) = m/, (\d+)? ?\((\d+)\)$/;
if (defined $number) {
print "color=C, number=$number\n";
}
else {
print "Line #$line is malformed!\n";
}
}
}
}
data.txt
contains this:
Sorcery, R (1)
Creature — Beast 5/3, 4G (5)
Sorcery, 1WWU (4)
Legendary Land
Artifact, (0)
Legendary Creature — Eldrazi 15/15, 15 (15)
There's just one difference from what you posted: the "Artifact" line in your question doesn't have parentheses around the 0 value, which would require an exception to be made in the parser. This can be added, but I don't see why that's better than fixing the format of the data file.
I assume you don't simply want the color and number values printed out, as this script does. You would put your own code in for each of the print
lines.
The $junk
bit comes from my assumption that the digit before the color letter(s) might be significant. I'm using it to help the parser do its thing. If you have a real use for this digit, you can rename the $junk
variable to have semantic meaning. It's only "junk" to me, because I don't know what the value means.