command line - grep - exclude string which is not a substring of a string - Ask Ubuntu


i explain problem on ubuntu 16.04 following example: file is:

# cat file aaa aaaxxx aaaxxx*aaa aaa=aaaxxx bbbaaaccc aaaddd/aaaxxx 

i want display lines contain aaa not in only combination of aaaxxx. want output this:

# grep something-here file … aaa aaaxxx*aaa (second aaa hit) aaa=aaaxxx (first aaa hit) bbbaaaccc (aaa in other combination not aaaxxx) aaaddd/aaaxxx (similar above) 

i tried things grep -v aaaxxx file | grep aaa results:

aaa bbbaaaccc 

or

# egrep -p '(?<!aaaxxx )aaa' file grep: die angegebenen suchmuster stehen in konflikt zueinander (the pattern in contradiction) 

is there (simple) possibility? of course doesn’t need grep. thanks

it's straightforward using perl-style lookahead operator - available in grep's perl compatible regular expression (pcre) mode using -p switch:

$ grep -p 'aaa(?!xxx)' file aaa aaaxxx*aaa aaa=aaaxxx bbbaaaccc aaaddd/aaaxxx 

(bold formatting in output indicates matched parts highlighted grep)


although zero-length lookahead convenient, achieve same output using gnu extended regular expression (ere) syntax, example matching aaa followed 2 x characters followed non-x character or end-of-line i.e.

grep -e 'aaax{0,2}([^x]|$)' file 

or using gnu basic regular expression (bre) syntax

grep 'aaax\{0,2\}\([^x]\|$\)' file 

which match

aaa aaaxxx*aaa aaa=aaaxxx bbbaaaccc aaaddd/aaaxxx

Comments

Popular posts from this blog

download - Firefox cannot save files (most of the time), how to solve? - Super User

windows - "-2146893807 NTE_NOT_FOUND" when repair certificate store - Super User