Search code examples
linuxshellgrep

grep with exclude pattern in shell


text file has below lines named 'log'

--- [n-event-group-3] action
--- [n-event-group-8] action.service
--- [n-event-group-2] essing.service.
--- [n-event-group-10] service.
--- [ost-stats-event] host.
--- 1077916, partition: 10, 
--- [d | vm-cm-event] cm.service.
--- [d | vm-cm-eve] cm.service
error: not found
com.rom.nom
--- [-event-group-11] ervice
--- [-event-group-15] ervice
--- [-event-group-20] ervice
--- [-event-group-99] ervice
--- [-event-group-13] ervice
--- [-event-group-13] ervice
--- [-event-group-13] ervice
--- [-event-group-13] ervice

want to grep lines containing [-event-group-13] and all line which does not have pattern [-event-group-(digits)]

so result needed is

--- [ost-stats-event] host.
--- 1077916, partition: 10, 
--- [d | vm-cm-event] cm.service.
--- [d | vm-cm-eve] cm.service
error: not found
com.rom.nom
--- [-event-group-13] ervice
--- [-event-group-13] ervice
--- [-event-group-13] ervice
--- [-event-group-13] ervice

I tried grep -vE '-event-group-[^13]' log but returns lines with

[n-event-group-3]
[n-event-group-10]
[n-event-group-11]
[n-event-group-15]

as well.


Solution

  • awk better fits your needs here:

    $ awk '!/-event-group-/{print} /-event-group-13/{print}' file
    
    --- [ost-stats-event] host.
    --- 1077916, partition: 10, 
    --- [d | vm-cm-event] cm.service.
    --- [d | vm-cm-eve] cm.service
    error: not found
    com.rom.nom
    --- [-event-group-13] ervice
    --- [-event-group-13] ervice
    --- [-event-group-13] ervice
    --- [-event-group-13] ervice