Charles
Charles

Reputation: 11479

Grepping only certain lines of files

I have a collection of files in a directory which I would like to search for a particular regular expression (=([14-9]|[23][0-9]), as it happens). But I only care when this pattern falls on the second, sixth, tenth, ..., 4n+2-th line.

Is there a good way to do this?

Upvotes: 1

Views: 213

Answers (3)

ghostdog74
ghostdog74

Reputation: 342273

modification to the answer without using extra grep,

awk '/(=([14-9]|[23][0-9])/ && FNR % 4==2{print FNR":"$0}}' inputFile 

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 881113

You should pass it through awk first to get rid of the unwanted lines (and optionally put on line numbers so that you can still tell what the real lines are):

pax> echo 'L1
...> L2
...> L3
...> L4
...> L5
...> L6
...> L7
...> L8
...> L9
...> L10
...> L11
...> L12' | awk '{if ((FNR % 4)==2) {print FNR":"$0}}'
2:L2
6:L6
10:L10

(just use '{if ((FNR % 4)==2) {print}}' if you don't care about the line numbers). So something like:

awk '{if ((FNR % 4)==2) {print FNR":"$0}}' inputFile | grep '(=([14-9]|[23][0-9])'

should do the trick.

Upvotes: 1

Pierre
Pierre

Reputation: 35226

try to do this with awk. Someting like

BEGIN     {i=0; n=0; }

/yourregegex/  {
               if(i==n) { print $0; n= 4*i+2;}
               }

               {
               i++;
               }

Upvotes: 1

Related Questions