将文件从多个目录复制到单个目标目录 [英] Copying files from multiple directories into a single destination directory

查看:68
本文介绍了将文件从多个目录复制到单个目标目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有多个目录,其中包含一个具有相同名称的文件:

There are multiple directories which contain a file with the same name:

direct_afaap/file.txt
direct_fgrdw/file.txt
direct_sardf/file.txt
...

现在,我想将它们提取到另一个目录 direct_new 中,并使用其他文件名,例如:

Now I want to extract them to another directory, direct_new and with a different file name such as:

[mylinux~ ]$ ls direct_new/
file_1.txt  file_2.txt  file_3.txt

我该怎么做?

顺便说一句,如果我想将原始目录中的部分名称放入文件名中,例如:

BTW, if I want to put part of the name in original directory into the file name such as:

[mylinux~ ]$ ls direct_new/
file_afaap.txt  file_fgrdw.txt  file_sardf.txt

我该怎么办?

推荐答案

这个小小的BaSH脚本将同时实现两种方式:

This little BaSH script will do it both ways:

#!/bin/sh
#

# counter
i=0

# put your new directory here
# can't be similar to dir_*, otherwise bash will
# expand it too
mkdir newdir

for file in `ls dir_*/*`; do
    # gets only the name of the file, without directory
    fname=`basename $file`
    # gets just the file name, without extension
    name=${fname%.*}
    # gets just the extention
    ext=${fname#*.}

    # get the directory name
    dir=`dirname $file`
    # get the directory suffix
    suffix=${dir#*_}

    # rename the file using counter
    fname_counter="${name}_$((i=$i+1)).$ext"

    # rename the file using dir suffic
    fname_suffix="${name}_$suffix.$ext"

    # copy files using both methods, you pick yours
    cp $file "newdir/$fname_counter"
    cp $file "newdir/$fname_suffix"
done

输出:

$ ls -R
cp.sh*
dir_asdf/
dir_ljklj/
dir_qwvas/
newdir/
out

./dir_asdf:
file.txt

./dir_ljklj:
file.txt

./dir_qwvas:
file.txt

./newdir:
file_1.txt
file_2.txt
file_3.txt
file_asdf.txt
file_ljklj.txt
file_qwvas.txt

这篇关于将文件从多个目录复制到单个目标目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆