是否可以从 find 命令输出中删除根目录? [英] Is it possible remove the root directory from find command output?
问题描述
我想移动一些文件,并认为 find 是选择正确文件的不错选择.所以我寻找文件:
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
-magic-option
是什么?
显然,简单的打印输出不是我的想法.最后一个命令也有一个-exec".类似的东西:
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.
如果问题的答案是'否',那没关系.我有一个使用 pushd
和 for
循环的粗略计划 B.但是 find
会更优雅.
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.
推荐答案
它是非标准的,但使用 gnu find (4.6.0.225-235f),你可以这样做:
It is non-standard, but with gnu find (4.6.0.225-235f), you could do:
find somedir -iname somefile -printf %P\\n
来自文档:
%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
这篇关于是否可以从 find 命令输出中删除根目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!