bash - Keep only nth line if keyword present -


assume text file contains lines starting foo , bar, respectively. assume further print every fourth line of ones starting bar; lines starting foo should printed.

foo bar qux    # deliberate empty line bar baz 1 bar baz 2 bar baz 3 bar baz 4 bar baz 5 bar baz 6 bar baz 7 bar baz 8 # miscellaneous code comment 

the following code prints every fourth line irrespective of first word , not looking for.

awk '/^bar/ nr == 1 || nr % 4 == 0' infile 

what correct code (preferentially awk)?

edit:

thanks fedorqui excellent suggestion. considering potential appearance of empty lines , comments in input file, using following code:

user$ awk '!/^bar/ || (/^bar/ && !(++c%4))' file foo bar qux    # deliberate empty line bar baz 4 bar baz 8 # miscellaneous code comment 

just use counter:

awk '/^foo/ || (/^bar/ && !(++c%4))' file 

this prints lines accomplish either of these:

  • start "foo"
  • start "bar" , happens 4th time, 8th... is, every 4 times line starts "bar".

see in action:

$ cat foo1 bar1 bar2 bar3 foo2 foo3 bar4 bar5 bar6 bar7 bar8 bar9 $ awk '/^foo/ || (/^bar/ && !(++c%4))' foo1 foo2 foo3 bar4 bar8 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -