311

The following grep expression successfully lists all the .exe and .html files in the current directory and sub directories.

ls -R |grep -E .*[\.exe]$\|.*[\.html]$  

How do I invert this result to list those that aren't a .html or .exe instead. (That is, !=.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sMaN
  • 3,667
  • 4
  • 23
  • 33

5 Answers5

433

Use command-line option -v or --invert-match,

ls -R |grep -v -E .*[\.exe]$\|.*[\.html]$
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eric Fortis
  • 16,372
  • 6
  • 41
  • 62
  • 13
    It should be noted that `-v`/`--invert-match` will not necessarily flip whether the return code of `grep` indicates successful execution, but will instead match the lines which would otherwise not be matched. Those who are looking to invert the return code (i.e. succeed if all of the lines do not match the pattern, rather than at least one) should use `! grep`. This finds use in conditional expressions, e.g.: `if ! ls | grep -qE ".(\.exe)$"; then echo No .exe files in $(pwd); fi`. – Zyl Oct 23 '18 at 15:51
  • I could not get the above to work, but this worked for me: `ls -R | grep -v -E ".*(\.exe)$|.*(\.vue)$"` – mlunoe Mar 09 '21 at 14:57
126
grep -v

or

grep --invert-match

You can also do the same thing using find:

find . -type f \( -iname "*" ! -iname ".exe" ! -iname ".html"\)

More info here.

darioo
  • 46,442
  • 10
  • 75
  • 103
  • 3
    The `find` command is the most semantic solution to this XY problem. Combining `ls` and `grep` for this purpose seems hacky at best. This should be the accepted answer. (+1) – Eric Seastrand May 03 '16 at 15:17
  • 5
    @Eric Regardless of the OP's requirements, inverting a grep expression is useful for much more than finding files. I doubt that's the reason most people come here. – byxor Aug 03 '17 at 10:42
37

Add the -v option to your grep command to invert the results.

Rob Sobers
  • 20,737
  • 24
  • 82
  • 111
24

As stated multiple times, inversion is achieved by the -v option to grep. Let me add the (hopefully amusing) note that you could have figured this out yourself by grepping through the grep help text:

grep --help | grep invert

-v, --invert-match select non-matching lines

jmd_dk
  • 12,125
  • 9
  • 63
  • 94
16
 grep "subscription" | grep -v "spec"  
Anja Ishmukhametova
  • 1,535
  • 16
  • 14