7

I have a lot of lines in my LIST file and want to list only lines whose name does not start by (or contains) "git".

So far I have :

cat LIST | grep ^[^g]

but I would like something like :

#not starting by "git"
cat LIST | grep ^[^(git)]
#not containing "git"
cat LIST | grep .*[^(git)].*

but it is not correct. What regex should I use ?

16

Using grep in this case with -P option, which Interprets the PATTERN as a Perl regular expression

grep -P '^(?:(?!git).)*$' LIST

Regular expression explanation:

^             the beginning of the string
 (?:          group, but do not capture (0 or more times)
   (?!        look ahead to see if there is not:
     git      'git'
   )          end of look-ahead
   .          any character except \n
 )*           end of grouping
$             before an optional \n, and the end of the string

Using the find command

find . \! -iname "git*"
  • 1
    Not sure how/if the expression would be optimzed internally, but I wouldn't use the quantifier + on the outer group. Considering it won't capture its match I'd simply remove it alltogether for a more simple/readable expression. – Mario Oct 13 '13 at 9:50
  • This expression will match anything from start to end of a line that does not start with git – hwnd Oct 13 '13 at 14:27
  • Your first command is what I am looking for :) However I do not understand what (?!git) does ? – Vulpo Oct 13 '13 at 16:28
  • It is a negative look ahead assertion, see updated edit. – hwnd Oct 13 '13 at 16:33
7

Since the OP is looking for a general regex and not specially for grep, this is the general regex for lines not starting with "git".

^(?!git).*

Breakdown:

^ beginning of line

(?!git) not followed by 'git'

.* followed by 0 or more characters

2

If you want to simply list all lines that don't contain git try this

 cat LIST | grep -v git
  • In that specific case, it does work. Thanks. But I would have preferred the use of regular expressions since it can be used in much more cases (for exemple a perl script parsing a user input). – Vulpo Oct 8 '13 at 11:15
  • Maybe this post on SO has what you need. – dinesh Oct 8 '13 at 16:55
  • Almost. I try to match what does NOT contain the string. Without using "-v" option from grep if possible :) – Vulpo Oct 11 '13 at 9:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.