![](/img/trans.png)
[英]How to find all sub directories containing a particular file and then grep another file in those sub-directories?
[英]Shell - Recursively find sub-directories and copy containing files to another directory
我有以下目录/文件结构:
/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
使用for i in {a..z}; do mkdir ordner${i}; done
创建了子目录for i in {a..z}; do mkdir ordner${i}; done
for i in {a..z}; do mkdir ordner${i}; done
for i in {a..z}; do mkdir ordner${i}; done
,但我不知道如何创建子目录以及如何复制文件。 我试过类似find /test/ -type d -name ".dir_pic" | xargs -0 -I%%% cp %%%/${i}*.jpg /test2/
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.