Grep --exclude-dir (root only)

I am trying to configure a grep command that searches for my current directory but excludes the directory only if it is the root directory.

So, for the following directories, I want # 1 to be excluded and # 2 to be included

1) vendor/phpunit 2) app/views/vendor 

First I started with the command below

 grep -Ir --exclude-dir=vendor keywords * 

I tried using ^ vendor, ^ vendor /, ^ vendor /, ^ vendor, but nothing works.

Is there any way to do this with grep? I tried to try to do this with a single grep call, but if I need to, I can pass the results to a second grep.

+4
source share
2 answers

With pipes:

 grep -Ir keywords * | grep -v '^vendor/' 

The problem with exclude-dir is that it checks the directory name and not the path to its entry, so it is not possible to distinguish between two vendor directories based on their depths.

+1
source

Here is the best solution that will actually ignore the specified directory:

 function grepex(){ excludedir="$1" shift; for i in *; do if [ "$i" != "$excludedir" ]; then grep $@ "$i" fi done } 

You use it as a replacement in grep, just select the excluded directory as the first argument and leave * at the end. So your command will look like this:

 grepex vendor -Ir keywords 

This is not ideal, but as long as you don't have really weird folders (e.g. with type names -- or something else), it will cover most use cases. Feel free to refine it if you want something more complex.

0
source

Source: https://habr.com/ru/post/1495818/


All Articles