Text Processing...print the 1st occurrence of pattern1 and 8th and 9th occurrence of pattern 2

StackOverflow https://stackoverflow.com/questions/19609925

  •  01-07-2022
  •  | 
  •  

سؤال

I have a text file and I want to print the 1st line starting with pattern "abcd" and also the 8th and 9th lines which are started with "DDD" pattern. Any sed or awk for doing that?

هل كانت مفيدة؟

المحلول

This should work for you:

awk '/^abcd/{p++;if(p==1) print}/^DDD/{q++;if(q==8||q==9)print}' file

نصائح أخرى

perl -lne 'push @{ $h->{$1} }, $_ if /.*(abcd|DDD).*/;END{print join "\n", @{ $h->{abcd}}[0]; print join "\n", @{ $h->{DDD}}[7..8];}' file

or decomposed :

perl -lne '
    push @{ $h->{$1} }, $_ if /.*(abcd|DDD).*/;
    END{
        print join "\n", @{ $h->{abcd} }[0], @{ $h->{DDD} }[7..8];
    }
' file
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top