Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find/grep all paths where directory name matches "x" but not "y" on *nix?

I have a folder structure like this (which is a small snippet):

└── test
    └── cases
        └── model
            ├── client
            │   ├── socketsTest.coffee
            ├── server
            │   └── socketsTest.coffee
            └── shared
                └── findersTest.coffee

The question is, how do you list all paths that end in .coffee and don't exist in the client folder?

The following command returns all files matching .coffee that exist in the server folder:

find test -name "*Test.coffee" | egrep '/*server*/'

But what I really need is a regex that matches everything except what's in the client folder.

What is the cleanest way to do this on *nix? The end goal is to return files not inside a client folder, so for the above tree that would be:

$ <find files except those a client folder>
test/cases/model/server/socketsTest.coffee
test/cases/model/shared/findersTest.coffee

I tried doing something like this but no luck:

find test -name "*Test.coffee" | egrep '*model/[^client]*'
like image 435
Lance Avatar asked Sep 04 '12 01:09

Lance


People also ask

Can you use wildcards with grep?

In grep the asterisk only matches multiples of the preceding character. The wildcard * can be a substitute for any number of letters, numbers, or characters. Wildcards can specify a group of letters or numbers. Wildcards can specify a group of letters or numbers.

What option can you use with grep to find all lines that do not include the regular expression?

If you want to find all lines that do not contain a specified pattern, you can use the -v or --invert-match option.

How do I grep all files in a directory for a string?

To search all files in the current directory, use an asterisk instead of a filename at the end of a grep command. The output shows the name of the file with nix and returns the entire line.

How do you use grep command to find a pattern in a directory?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.


1 Answers

You can use the -prune action to ignore directories. -o means "or", so read this as, "if it's named client prune it, otherwise print files named *.coffee".

find test -name client -prune -o -name '*.coffee' -print

Or you can use a double test, which is easier to read but slightly less efficient, since it'll recurse into client/ directories, whereas the first one avoids them entirely.

find test -name '*.coffee' ! -wholename '*/client/*'
like image 173
John Kugelman Avatar answered Sep 21 '22 01:09

John Kugelman