我想使用find
递归列出给定根目录中的所有文件和目录以进行cpio
操作。但是,我不希望根目录本身出现在路径中。例如,我目前得到:
$ find diskimg
diskimg
diskimg/file1
diskimg/dir1
diskimg/dir1/file2
Run Code Online (Sandbox Code Playgroud)
但是,我想得到
file1
dir1
dir1/file2
Run Code Online (Sandbox Code Playgroud)
(注意根也不在我想要的输出中,但这很容易摆脱tail
)。
我在 OS X 上,如果可能的话,我不想安装任何额外的工具(例如 GNU find),因为我想与其他 OS X 用户共享我正在编写的脚本。
我知道这可以通过cut
切断根目录来完成,但这似乎是一个次优的解决方案。有更好的解决方案吗?
Ste*_*han 36
cd
先进入目录:
cd diskimg && find .
Run Code Online (Sandbox Code Playgroud)
完成后,您将回到根目录。
在这种情况下,您的文件将以 ./ 开头;我看到的唯一方法是使用cut
:
{ cd diskimg && find .; } | tail -n +2 | cut -c 3-
Run Code Online (Sandbox Code Playgroud)
使用子shell 避免更改shell 的当前目录(如果您正在管道输出,因为管道的左侧已经在子shell 中运行,所以这不是必需的)。
(cd diskimg && find .)
Run Code Online (Sandbox Code Playgroud)
Ste*_*han 30
另一个更复杂但仅使用我的其他答案中的 find 方法:
find diskimg -mindepth 1 -printf '%P\n'
Run Code Online (Sandbox Code Playgroud)
Bri*_*Guy 21
如果你想做的不是太复杂,你可以用 sed 来完成:
find diskimg | sed -n 's|^diskimg/||p'
Run Code Online (Sandbox Code Playgroud)
或者cut
:
find diskimg | cut -sd / -f 2-
Run Code Online (Sandbox Code Playgroud)
小智 17
使用该realpath
实用程序:
find diskimg -exec realpath --relative-to diskimg {} \;
Run Code Online (Sandbox Code Playgroud)