linux - 将文件从多个目录复制到一个目标目录

标签 linux bash shell

有多个目录包含同名文件:

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

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

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

我该怎么做?

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

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

我能做什么?

最佳答案

这个小的 BaSH 脚本将以两种方式完成:

#!/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

关于linux - 将文件从多个目录复制到一个目标目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44460177/

相关文章:

linux - Julia - Julia 如何处理变量?

c - 如何在 c 中的两个程序之间共享库

c - C 中的简单 Linux Bindshell - 将 Shell 控制返回给客户端

linux - 为什么 read 在 bash 中抛出错误但工作正常?

bash - 使用匹配文件在循环中调用程序

c - C UNIX shell 中的管道

linux - 递归加入 N 行

bash - 使用 sed 替换动态生成的字符串

linux - 如何在 linux 中增加变量的一部分

linux - 如何在gpio上循环?