如何打印匹配的行以及之前和之后的行?我现在有:
perl -lane 'print if $F[3] > 100000 && $F[2] =~ /^C$/ && print $last; $last = $_'
能够在之前打印匹配的行和行 - 但我不知道如何在之后包含行。
答案 0 :(得分:4)
您可以使用scalar <>
直接从文件中读取下一行:
perl -lane 'print, print scalar <>
if $F[3] > 100000 && $F[2] =~ /^C$/
&& print $last;
$last = $_' input
或者使用滑动窗口来重叠匹配:
perl -ane 'BEGIN { @b = map [], 1 .. 3 }
sub out {
shift @b;
if ($b[1][3] > 100_000 && $b[1][2] =~ /^C$/) {
print for map $_->[-1], @b;
}
}
push @b, [@F, $_];
out()
}{ out() # Process the last line
' input
答案 1 :(得分:1)
以下处理重叠匹配。 $N
是在匹配行之前和之后打印的行数。
perl -lane'
BEGIN { $N = 1 }
if ($F[3] > 100000 && $F[2] =~ /^C$/) { print for splice(@buf), $_; $next=$N }
elsif ($next) { --$next; print }
else { push @buf, $_; splice @buf, 0, -$N }
'
由于我们知道$N = 1
,我们可以将上述内容简化为以下内容:
perl -lane'
if ($F[3] > 100000 && $F[2] =~ /^C$/) { print for splice(@buf), $_; $next=1 }
elsif ($next) { $next=0; print }
else { @buf = $_ }
'
答案 2 :(得分:0)
您还可以使用// Input: v is an array of k unique elements, each in the
// range [0, n)
// Output: The index of v in the set of all possible such vectors.
int permindex(int n, int k, int* v) {
int val[n], pos[n];
// This initialization would probably have been better as
// for (int i = 0; i < n; ++i) val[i] = pos[i] = i;
// The "optimization" below is intended to show that this
// entire operation is O(k) rather than O(n); it involves
// only initializing elements in the val and pos arrays which
// we might actually reference.
for (int i = 0; i < k; ++i) {
val[i] = i;
pos[v[i]] = v[i];
}
int index = 0;
for (int i = 0; i < k; ++i) {
int loc = pos[v[i]];
index *= n - i;
index += loc - i;
pos[val[i]] = loc;
val[loc] = val[i];
}
return index;
}
和seek
并重绕一行以重叠匹配:
tell