3

Suppose I have this going:

$ find ./src -name '*.txt'
./src/file1.txt
./src/subdir1/file2.txt
./src/subdir1/subsubdir1/file3.txt
./src/subdir2/file4.txt

I want to exclude the directory being searched, so something like:

./file1.txt instead of ./src/file1.txt
./subdir1/file2.txt instead of ./src/subdir1/file2.txt and so on.

Adding -mindepth 1 didn't do anything.

Is it possible to do what I'm after purely in find?

2

2 Answers 2

9

For situations where you don't have a version of find that supports -printf '%P' you can use this alternative structure to avoid including the search path.

Starting point as in the question:

find ./src -name '*.txt'

Same but without the search path in the results

( cd ./src && find . -name '*.txt' )

Assuming the file structure shown in your question, the result is

./file1.txt
./subdir1/file2.txt
./subdir1/subsubdir1/file3.txt
./subdir2/file4.txt
5

Expanding on what @steeldriver said:

$ cd "$(mktemp --directory)" # create temporary directory
direnv: unloading
$ mkdir foo bar
$ touch foo/1 bar/2
$ find foo bar -type f -name '*' -printf '%P\n'
1
2

The %P formatting string is documented as follows by the GNU find manual:

%P
File's name with the name of the starting-point under which it was found removed.

Here, "file's name" means the pathname of the found file, not just the filename.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .