![find & cp 命令不复制一级目录](https://linux22.com/image/226744/find%20%26%20cp%20%E5%91%BD%E4%BB%A4%E4%B8%8D%E5%A4%8D%E5%88%B6%E4%B8%80%E7%BA%A7%E7%9B%AE%E5%BD%95.png)
我有一个这样的目录结构:
test folders
├── 1
│ ├── 1-1
│ ├── 1-2
│ └── 1-3
├── 2
│ ├── 2-1
│ ├── 2-2
│ └── 2-3
├── 3
│ ├── 3-1
│ ├── 3-2
│ └── 3-3
└── 4
├── 4-1
├── 4-2
└── 4-3
16 directories, 0 files
我正在努力仅复制第一级文件夹 - 1,2,3,4 不包括使用 find & cp 命令的所有子文件夹
├── 1
├── 2
├── 3
└── 4
工作目录是:“/home/用户名/Downloads/test 文件夹”
我用了
username@username-desktop:~/Downloads/test folders$ find . -maxdepth 1 -type d
输出是
.
./2
./3
./4
./1
如果我将命令的第一部分与 cp: 结合起来,find . -maxdepth 1 -type d -exec cp -p -v "{}" "/home/username/Downloads/results" \;
那么结果是:
username@username-desktop:~/Downloads/test folders$ find . -maxdepth 1 -type d -exec cp -p -v "{}" "/home/username/Downloads/results" \;
cp: -r not specified; omitting directory '.'
cp: -r not specified; omitting directory './2'
cp: -r not specified; omitting directory './3'
cp: -r not specified; omitting directory './4'
cp: -r not specified; omitting directory './1'
所以然后我在上面的命令中添加了 -r 开关:
username@username-desktop:~/Downloads/test folders$ find . -maxdepth 1 -type d -exec cp -p -r -v "{}" "/home/username/Downloads/results" \;
'./1' -> '/home/username/Downloads/results/./1'
'./1/1-1' -> '/home/username/Downloads/results/./1/1-1'
'./1/1-2' -> '/home/username/Downloads/results/./1/1-2'
'./1/1-3' -> '/home/username/Downloads/results/./1/1-3'
'./2' -> '/home/username/Downloads/results/./2'
'./2/2-1' -> '/home/username/Downloads/results/./2/2-1'
'./2/2-2' -> '/home/username/Downloads/results/./2/2-2'
'./2/2-3' -> '/home/username/Downloads/results/./2/2-3'
'./3' -> '/home/username/Downloads/results/./3'
'./3/3-1' -> '/home/username/Downloads/results/./3/3-1'
'./3/3-2' -> '/home/username/Downloads/results/./3/3-2'
'./3/3-3' -> '/home/username/Downloads/results/./3/3-3'
'./4' -> '/home/username/Downloads/results/./4'
'./4/4-1' -> '/home/username/Downloads/results/./4/4-1'
'./4/4-2' -> '/home/username/Downloads/results/./4/4-2'
'./4/4-3' -> '/home/username/Downloads/results/./4/4-3'
所以现在结果文件夹有:
results
├── 1
│ ├── 1-1
│ ├── 1-2
│ └── 1-3
├── 2
│ ├── 2-1
│ ├── 2-2
│ └── 2-3
├── 3
│ ├── 3-1
│ ├── 3-2
│ └── 3-3
└── 4
├── 4-1
├── 4-2
└── 4-3
这是如何复制所有子文件夹的?即使我包含了 -r 但我也从 find 命令的一开始就包含了 - maxdepth 1 。我如何理解为什么会发生这种情况?
[编辑] 后续问题链接至此处:如何用cp排除不同级别的子目录?
答案1
-maxdepth 1
是一个指令find
。因为它,你的意志会为之find
奔跑,而它不会为之奔跑;等等。请注意,它将首先运行。cp …
./1
cp …
./1/1-1
cp …
.
当你find
跑步时cp -p -r -v . /home/username/Downloads/results
,cp
不在乎-maxdepth 1
。它只看到自己的论据。并且这个确切的命令将./1/1-1
由于-r
.
看这个:了解-exec
选项find
。没有什么魔法,find -exec
构建并运行独立的命令。