Martin
Martin

Reputation: 11875

Is it possible remove the root directory from find command output?

I want to move some files around and thought that find would be a good option to select the correct files. So I look for the files:

find somedir -iname "somefile"
somedir/subdir1/subdir2/somefile
somedir/subdir2/somefile
somedir/subdir3/somefile
somedir/subdir4/somefile
somedir/subdir5/somefile

Thats not very helpful for what I'm planning next. What I need would be:

find somedir -iname "somefile" -magic-option
subdir1/subdir2/somefile
subdir2/somefile
subdir3/somefile
subdir4/somefile
subdir5/somefile

What would -magic-option be?

Obviously a simple printout is not what I had in mind. The final command will also have a '-exec'. Something like:

find somedir -iname "somefile" -magic-option -exec some_command 'somedir/{}' 'someotherdir/{}' ';'

I'm surprised I couldn't find anything as removing the root directory from the result seem a pretty obvious feature.

If the answer to the question is 'NO' then that's ok. I have a crude plan B using pushd and for loops. But find would be more elegant.

Upvotes: 1

Views: 1384

Answers (2)

William Pursell
William Pursell

Reputation: 212584

It is non-standard, but with gnu find (4.6.0.225-235f), you could do:

find somedir -iname somefile -printf %P\\n

From the documentation:

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

If you want a generic solution, it seems simple enough to filter the output with something like:

find somedir -iname somefile | sed 's@^[^/]*/@@'

Both of those solutions will fail horribly if any of your filenames contain a newline, so if you want a robust solution you would want to do something like:

find somedir -iname somefile -printf %P\\0

Upvotes: 4

Raman Sailopal
Raman Sailopal

Reputation: 12907

Looks like you need the mindepth flag.

find somedir -mindepth 2 -iname "somefile"

This will ignore the directory you are in and search from one level down recursively.

Upvotes: 0

Related Questions