我有右眼和左眼的file_test
个值
如何通过awk将file_test
分隔为file1
和file2
,以便将相等的值写入file1
,将不同的值写入file2
,如下例所示
file_test
是:
NAME: jim
LAST NAME: bakker
right eye: >|5|<
left eye VALUE: >|5|<
NAME: Jorg
LAST NAME: mitchel
right eye: >|3|<
left eye VALUE: >|5|<
NAME: jimmy
LAST NAME: kartter
right eye: >|6|<
left eye VALUE: >|5|<
NAME: david
LAST NAME: kann
right eye: >|9|<
left eye VALUE: >|9|<
file1
应该是:
NAME: jim
LAST NAME: bakker
right eye: >|5|<
left eye VALUE: >|5|<
NAME: david
LAST NAME: kann
right eye: >|9|<
left eye VALUE: >|9|<
file2
应该是:
NAME: Jorg
LAST NAME: mitchel
right eye: >|3|<
left eye VALUE: >|5|<
NAME: jimmy
LAST NAME: kartter
right eye: >|6|<
left eye VALUE: >|5|<
答案 0 :(得分:1)
awk -F: '/^NAME:/ && buff {
say(buff, eyes); buff = null
split(null, eyes) # use delete eyes if supported
}
{
buff = buff ? buff RS $0 : $0
/eye/ && eyes[$NF]
}
END { say(buff, eyes) }
func say(b, e) {
# length(array) is not portable
print b > (length(e) > 1 ? "file2" : "file1")
}' file_test
答案 1 :(得分:0)
我会使用Perl:
open my $f, "<", "file_input";
open my $file1, ">", "file1";
open my $file2, ">", "file2";
while (! eof($f)) {
my $person; $person .= <$f> for (1..4); # read 4 lines
my ($right) = ($person =~ /^right.*?(\d+)/m);
my ($left) = ($person =~ /^left.*?(\d+)/m);
my $file = ($right == $left) ? $file1 : $file2;
print $file $person;
}
close $f;
close $file1;
close $file2