Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excluding directories with grep

Tags:

linux

grep

ubuntu

I just tried:

michael@Pascal:~/noisynet$ sudo grep -rio --exclude-dir={/ece,/home/michael/pytorch,/sys,/proc} 'hello' /

The very first match is:

/home/michael/pytorch/.git/logs/HEAD:hello

Why is it looking in /home/michael/pytorch?

like image 479
MichaelSB Avatar asked Sep 05 '19 22:09

MichaelSB


People also ask

How do I exclude a directory in grep?

You would need --exclude-dir="dir1" , which excludes elsewhere/dir1 as well. Note that if a directory is excluded, its subdirectories are excluded as well, so --exclude-dir="dir1" also excludes files in . config/dir1/dir2 . If grep's exclude patterns aren't sufficient for you, you can combine find with grep .

How do you exclude a directory?

Go to Start > Settings > Update & Security > Windows Security > Virus & threat protection. Under Virus & threat protection settings, select Manage settings, and then under Exclusions, select Add or remove exclusions. Select Add an exclusion, and then select from files, folders, file types, or process.

How do I find and exclude a directory?

We can exclude directories by using the help of “path“, “prune“, “o” and “print” switches with find command. The directory “bit” will be excluded from the find search!

Can grep search directories?

The grep command is a useful Linux command for performing file content search. It also enables us to recursively search through a specific directory, to find all files matching a given pattern.


1 Answers

This will work well

grep -rio --exclude-dir={ece,pytorch,sys,proc} 'hello' /

Note: This will also exclude other directories with same name.

Explanation:

Man page of grep gives below snippet

   --exclude-dir=GLOB
          Skip  any command-line directory with a name suffix that matches the pattern GLOB.  When
          searching recursively, skip any subdirectory whose base name matches GLOB.   Ignore  any
          redundant trailing slashes in GLOB.

This means given pattern (GLOB) will be applied only to the actual name of the directory, and since a directory name don't contain / in its name, a pattern like /proc will never match.

Hence, we need to use --exclude-dir=proc or --exclude-dir=sys (or --exclude-dir={proc,sys}) just names for directories to be excluded without '/'.

like image 58
Avinash Yadav Avatar answered Sep 22 '22 07:09

Avinash Yadav