将子目录中的特定文件复制到一个目录中

Copy specific files from subdirectories into one directory

我有一个目录:

❯ find ./images -name *150x150.jpg
./images/2060511653921052666.images/thumb-150x150.jpg
./images/1777759401031970571.images/thumb-150x150.jpg
./images/1901716489977597520.images/thumb-150x150.jpg
./images/2008758225324557620.images/thumb-150x150.jpg
./images/1988762968386208381.images/thumb-150x150.jpg
./images/1802341648716075239.images/thumb-150x150.jpg
./images/2051017760380879322.images/thumb-150x150.jpg
./images/1974813836146304123.images/thumb-150x150.jpg
./images/2003120002653201215.images/thumb-150x150.jpg
./images/1911925394312129508.images/thumb-150x150.jpg
(...)

我想将所有这些文件 (thumb-150x150.jpg) 复制到一个目录中。

❯ find ./images -name *150x150.jpg -exec cp {} ./another-directory \;

当然,每个文件都会被下一个文件覆盖。

那么我如何将它们复制到:

1) 1.jpg, 2.jpg, 3.jpg...等等

2)使用子目录id(./images/2060511653921052666.images/thumb-150x150.jpg)作为目标文件名(本例中为2060511653921052666.jpg) ?

一个简单的 bash 脚本,使用 $RANDOM 为每个复制的图像生成一个随机数。每个文件的新名称中嵌入了一个随机数。

请注意,$RANDOM 生成一个介于 1 和 32767 之间的随机数。因此可以多次生成相同的随机数。这只有在您要复制数万张图像时才有可能。

提高生成的每个数字的随机性是相当容易的。

# !/bin/bash
cd images
for d in *
do
    [ -d $d ] && cd $d
    for image in *150x150.jpg
    do
        cp -pv $image /another-dir/thumb${RANDOM}.jpg
    done
    [ -d $d ] && cd ..
done

你可以使用循环:

i=1
find ./images -name *150x150.jpg | while read line; do
        cp $line /anotherdir/$i.jpg
        i=$[i+1]
done

如果您有 GNU parallel,则可能:

find ./images -name *150x150.jpg | \
parallel 'mv {} ./another-directory/`stat -c%i {}`_{/}'

stat -c%i {} 获取每个文件的索引节点

我在我的系统上测试了以下命令:

find -iname "*.mp3" | parallel 'cp {} ~/tmp/{/.}_`stat -c%i {}`.mp3'

{/} .......... gets just the filename with no full path "basename"
{.} .......... removes extension

在运行实际命令之前,您可以在 cp 或 mv 前面放置一个 echo 命令以测试您的命令。

来源: