302

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, !=.)

5 Answers 5

418

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

ls -R |grep -v -E .*[\.exe]$\|.*[\.html]$
2
  • 12
    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, 2018 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 9, 2021 at 14:57
125
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.

2
  • 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) May 3, 2016 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 3, 2017 at 10:42
37

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

22

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

15
 grep "subscription" | grep -v "spec"  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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