gpt4 book ai didi

linux - Shell - 递归查找子目录并将包含的文件复制到另一个目录

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:37:56 26 4
gpt4 key购买 nike

我有以下目录/文件结构:

/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} 创建了子目录;做 mkdir ordner${i};完成,但我不知道如何创建子目录以及如何复制文件。我尝试了类似 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

关于linux - Shell - 递归查找子目录并将包含的文件复制到另一个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46393326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com