-
Notifications
You must be signed in to change notification settings - Fork 0
/
srtmerge
executable file
·96 lines (82 loc) · 2.21 KB
/
srtmerge
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/perl
use strict;
use warnings;
# Processes $ARGV[0].
my %tshash;
my $tskey;
my @tsvs;
open(my $tsh, '<', $ARGV[0]) or die "Could not open file '$ARGV[0]' $!";
my @tslines = <$tsh>;
close($tsh);
@tslines = grep { $_ !~ /^ *$/ } @tslines;
for (my $i = 0; $i < @tslines; $i++) {
if ($tslines[$i] =~ /^(\d+)$/) {
if ($i + 1 < @tslines && $tslines[$i + 1] =~ /^\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}$/) {
# Appends '%-' for easy parsing.
$tslines[$i] =~ s/^(\d+)$/$1%-/;
}
}
}
# Constructs hashmap of number to (timestamp, text).
foreach my $line (@tslines) {
chomp $line;
if ($line =~ /^(\d+)%-/) {
if (defined $tskey) {
$tshash{$tskey} = [shift @tsvs, join("\n", @tsvs)];
}
$tskey = $1;
@tsvs = ();
} else {
push @tsvs, $line;
}
}
if (defined $tskey) {
$tshash{$tskey} = [shift @tsvs, join("\n", @tsvs)];
}
# Processes $ARGV[1].
my %hash;
my $key;
my $value = '';
open(my $fh, '<', $ARGV[1]) or die "Could not open file '$ARGV[1]' $!";
my @lines = <$fh>;
close $fh;
# Appends `%-` to each number, and removes timestamp.
for (my $i = 0; $i < @lines; $i++) {
if ($lines[$i] =~ /^(\d+)$/) {
if ($i + 1 < @lines && $lines[$i + 1] =~ /^\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}$/) {
$lines[$i] =~ s/^(\d+)$/$1%-/;
}
}
}
@lines = grep { $_ !~ /^[0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9][0-9][0-9]/ } @lines;
@lines = grep { $_ !~ /^ *$/ } @lines;
# Constructs hashmap of number to text
foreach my $line (@lines) {
chomp $line;
if ($line =~ /^(\d+) *% *-/) {
if (defined $key) {
$hash{$key} = $value;
}
$key = $1;
$value = '';
} else {
$value .= "$line\n";
}
}
if (defined $key) {
$hash{$key} = $value;
}
# Merges argv1 text to argv2 text
foreach my $tskey (sort { $a <=> $b } keys %tshash) {
print "$tskey\n";
print "$tshash{$tskey}->[0]\n";
if (exists $hash{$tskey} && $hash{$tskey} ne "") {
my $value = $hash{$tskey};
chomp $value;
print "$value\n\n";
} else {
my $value = $tshash{$tskey}->[1];
chomp $value;
print "$value\n\n";
}
}