Skip to content
Advertisement

How to use regex to match both filename and file content in Linux? [closed]

I want to find files that contain the word ‘virus’ but not ‘antivirus’ (case insensitive) in both their filename and their content.

Thanks for your help.

Advertisement

Answer

grep -i -P --exclude='*[aA][nN][tT][iI][vV][iI][rR][uU][sS]*' '(?<!anti)virus' *[vV][iI][rR][uU][sS]*

(?<!anti) is a negative lookbehind that prevents matching the following pattern if it’s preceded by anti.

The above operates just in the current directory. If you need to search subdirectories recursively, use:

grep -P -r -i --include='*[vV][iI][rR][uU][sS]*' --exclude='*[aA][nN][tT][iI][vV][iI][rR][uU][sS]*' '(?<!anti)virus' .
4 People found this is helpful
Advertisement