gpt4 book ai didi

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

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

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

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/

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