Search code examples
grep

grep every other occurrence of a value


I have an output file with multiple occurrences of a value. E.g.:

value 123  
value 111  
value 456  
value 111  
value 789  
value 111

If I use the following command, I can print all the occurrences of 'value':

grep 'value ' file_name

But I only want to print every other occurrence. Is there some way that I can edit my command to do this?


Solution

  • Use this Perl one-liner to filter the results of grep:

    grep 'value' file_name | perl -ne 'print if $. % 2;'
    

    The Perl one-liner uses these command line flags:
    -e : Tells Perl to look for code in-line, instead of in a file.
    -n : Loop over the input one line at a time, assigning it to $_ by default.

    $. : Current input line number.

    SEE ALSO:
    perldoc perlrun: how to execute the Perl interpreter: command line switches
    perldoc perlvar: Perl predefined variables