tags:

views:

33

answers:

2

hi I have in file file_test values of right eye and left eye How to separate the file_test to file1 and file2 by awk in order to write the equal values into file1 and different values into file2 as the following example down

file_test is:

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 should be:

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 should be:

NAME: Jorg  
LAST NAME: mitchel
right eye: >|3|< 
left eye VALUE: >|5|< 
NAME: jimmy  
LAST NAME: kartter
right eye: >|6|< 
left eye VALUE: >|5|<
A: 

I'd use Perl for this:

    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
glenn jackman
+1  A: 
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
radoulov
cryptic but concise
glenn jackman