2
값을 찾으면 동일한 값을 가진 모든 줄이 연속적으로 표시된다는 것을 의미하는 두 번째 열의 값을 정렬한다고 가정 할 때 하나의 해결책은 perl
입니다. 이 두 번째 열에서 다른 값을 찾을 때까지 스크립트가 선을 유지 카운트를 얻을, 그들을 인쇄 메모리를 해제, 그래서 관계없이 입력 파일이 얼마나 큰의 문제가 발생하지 않아야
내용 script.pl
의 :
use warnings;
use strict;
my (%lines, $count);
while (<>) {
## Remove last '\n'.
chomp;
## Split line in spaces.
my @f = split;
## Assume as malformed line if it hasn't four fields and omit it.
next unless @f == 4;
## Save lines in a hash until found a different value in second column.
## First line is special, because hash will always be empty.
## In last line avoid reading next one, otherwise I would lose lines
## saved in the hash.
## The hash will ony have one key at same time.
if (exists $lines{ $f[1] } or $. == 1) {
push @{ $lines{ $f[1] } }, $_;
++$count;
next if ! eof;
}
## At this point, the second field of the file has changed (or is last line), so
## I will print previous lines saved in the hash, remove then and begin saving
## lines with new value.
## The value of the second column will be the key of the hash, get it now.
my ($key) = keys %lines;
## Read each line of the hash and print it appending the repeated lines as
## last field.
while (@{ $lines{ $key } }) {
printf qq[%s\t%d\n], shift @{ $lines{ $key } }, $count;
}
## Clear hash.
%lines =();
## Add current line to hash, initialize counter and repeat all process
## until end of file.
push @{ $lines{ $f[1] } }, $_;
$count = 1;
}
infile
의
내용 :
foobar1 1 xxx yyy
foobar1 2 xxx yyy
foobar2 2 xxx yyy
foobar2 3 xxx yyy
foobar1 3 xxx zzz
실행이 좋아 :
perl script.pl infile
01 다음과 같은 출력으로 23,516,
:
foobar1 1 xxx yyy 1
foobar1 2 xxx yyy 2
foobar2 2 xxx yyy 2
foobar2 3 xxx yyy 2
foobar1 3 xxx zzz 2
PLS는 일부 샘플 데이터를 붙여 여러분의 기대 출력. – Kent