Shell - 递归查找子目录并将包含的文件复制到另一个目录
Shell - Recursively find sub-directories and copy containing files to another directory
我得到了以下 directory-/file 结构:
/test
/dir_a
/dir_pic
car.jpg
train.jpg
thumbs.db
/dir_b
/dir_pic
car.jpg
plane.jpg
boat.jpg
/dir_c
/dir_pic
ship.jpg
space_shuttle.jpg
我想复制创建以下结构的文件:
/test2
/c
/car
car.jpg
/b
/boat
boat.jpg
/p
/plane
plane.jpg
/s
/ship
ship.jpg
/space shuttle
space shuttle.jpg
/t
/train
train.jpg
我用 for i in {a..z}; do mkdir ordner${i}; done
创建了子目录,
但我不知道如何创建子目录以及如何复制文件。
我尝试了 find /test/ -type d -name ".dir_pic" | xargs -0 -I%%% cp %%%/${i}*.jpg /test2/
之类的方法,但这不起作用。
除此之外,for 循环不起作用,尤其是当路径包含空格时?
由于我的 Linux-知识非常有限,我恳请您帮助如何实现这一点 (Ubuntu 16.04 LTS)。
bash解法:
#!/bin/bash
dest_dir="/test2" # destination directory
for f in $(find /test/ -type f -path "*/dir_pic/*.jpg"); do
fn="${f##*/}" # filename (basename)
parent_d="${fn:0:1}" # parent directory
child_d="${fn%.*}" # child directory
if [[ ! -d "$dest_dir/$parent_d/$child_d" ]]; then
mkdir -p "$dest_dir/$parent_d/$child_d"
cp "$f" "$dest_dir/$parent_d/$child_d/$fn"
fi
done
查看结果:
$ tree /test2
|-- b
| `-- boat
| `-- boat.jpg
|-- c
| `-- car
| `-- car.jpg
|-- p
| `-- plane
| `-- plane.jpg
|-- s
| |-- ship
| | `-- ship.jpg
| `-- space_shuttle
| `-- space_shuttle.jpg
|-- t
| `-- train
| `-- train.jpg
我得到了以下 directory-/file 结构:
/test
/dir_a
/dir_pic
car.jpg
train.jpg
thumbs.db
/dir_b
/dir_pic
car.jpg
plane.jpg
boat.jpg
/dir_c
/dir_pic
ship.jpg
space_shuttle.jpg
我想复制创建以下结构的文件:
/test2
/c
/car
car.jpg
/b
/boat
boat.jpg
/p
/plane
plane.jpg
/s
/ship
ship.jpg
/space shuttle
space shuttle.jpg
/t
/train
train.jpg
我用 for i in {a..z}; do mkdir ordner${i}; done
创建了子目录,
但我不知道如何创建子目录以及如何复制文件。
我尝试了 find /test/ -type d -name ".dir_pic" | xargs -0 -I%%% cp %%%/${i}*.jpg /test2/
之类的方法,但这不起作用。
除此之外,for 循环不起作用,尤其是当路径包含空格时?
由于我的 Linux-知识非常有限,我恳请您帮助如何实现这一点 (Ubuntu 16.04 LTS)。
bash解法:
#!/bin/bash
dest_dir="/test2" # destination directory
for f in $(find /test/ -type f -path "*/dir_pic/*.jpg"); do
fn="${f##*/}" # filename (basename)
parent_d="${fn:0:1}" # parent directory
child_d="${fn%.*}" # child directory
if [[ ! -d "$dest_dir/$parent_d/$child_d" ]]; then
mkdir -p "$dest_dir/$parent_d/$child_d"
cp "$f" "$dest_dir/$parent_d/$child_d/$fn"
fi
done
查看结果:
$ tree /test2
|-- b
| `-- boat
| `-- boat.jpg
|-- c
| `-- car
| `-- car.jpg
|-- p
| `-- plane
| `-- plane.jpg
|-- s
| |-- ship
| | `-- ship.jpg
| `-- space_shuttle
| `-- space_shuttle.jpg
|-- t
| `-- train
| `-- train.jpg