2016-11-25 62 views
0

我正在使用Linux机器。 我有很多同名的文件,像这样的目录结构:Bash:如何将多个具有相同名称的文件复制到多个文件夹

P45_input_foo/result.dat 
P45_input_bar/result.dat 
P45_input_tar/result.dat 
P45_input_cool/result.dat ... 

难以通过一对一复制它们。我想将它们复制到命名为data类似的文件夹和文件的名称另一个文件夹:

/data/foo/result.dat 
/data/bar/result.dat 
/data/tar/result.dat 
/data/cool/result.dat ... 

在复制代替逐一我应该怎么办呢?

+1

您是在Linux还是Windows机器上?你需要一个“bash”或“批量”解决方案? – Inian

+0

@Inian我正在linux机器上工作。所以我需要一个bash解决方案。谢谢你提醒我 –

回答

1

在bash使用for循环:

# we list every files following the pattern : ./<somedirname>/<any file> 
# if you want to specify a format for the folders, you could change it here 
# i.e. for your case you could write 'for f in P45*/*' to only match folders starting by P45 
for f in */* 
do 
    # we strip the path of the file from its filename 
    # i.e. 'P45_input_foo/result.dat' will become 'P45_input_foo' 
    newpath="${f%/*}" 

    # mkdir -p /data/${newpath##*_} will create our new data structure 
    # - /data/${newpath##*_} extract the last chain of character after a _, in our example, 'foo' 
    # - mkdir -p will recursively create our structure 
    # - cp "$f" "$_" will copy the file to our new directory. It will not launch if mkdir returns an error 
    mkdir -p /data/${newpath##*_} && cp "$f" "$_" 
done 

${newpath##*_}${f%/*}用法是Bash的字符串操作方法的一部分。你可以阅读更多关于它here

+0

感谢您的回答,您能否提供更多详细信息? '{newpath ## * _}“'对我来说似乎很奇怪 –

+0

我不知道是谁投我票,你能帮我投票吗?我没有重复我的问题。 –

+0

@Lbj_x:我没有让你失望,但是谁做了这件事可能会这样做,因为你没有向我们展示任何你试图解决你的问题的代码。 – Inian

1

您需要后提取的第三个项目 “_”:

P45_input_foo - >富

创建目录(如果需要)和文件复制到它。事情是这样的(未测试,可能需要编辑):

STARTING_DIR="/" 
cd "$STARTING_DIR" 
VAR=$(ls -1) 
while read DIR; do 
    TARGET_DIR=$(echo "$DIR" | cut -d'_' -f3) 
    NEW_DIR="/data/$DIR" 
    if [ ! -d "$NEW_DIR" ]; then 
    mkdir "$NEW_DIR" 
    fi 
    cp "$DIR/result.dat" "$NEW_DIR/result.dat" 
    if [ $? -ne 0 ]; 
    echo "ERROR: encountered an error while copying" 
    fi 
done <<<"$VAR" 

说明:假设你提到的所有路径都在根/(如果不改变STARTING_PATH相应)。用ls可以得到目录列表,将输出存储在VAR中。将VAR的内容传递给while循环。

+0

嗨,可能是我没有正确解释。 P45_ *是一个目录中的一个PXX_ *系列。 –

+0

@Lbj_x对不起。我仍然没有明白你的意思。你能举个例子吗? –

+0

在起始目录中:我有P45_input_ *系列文件夹。和P46_ *和P47_ *等文件夹。我想我需要在开始时指定DIR? –

1

有点find和几个bash技巧,下面的脚本可以为你做的伎俩。请记住在没有mv的情况下运行该脚本,并查看"/data/"$folder"/"是否是要移动文件的实际路径。

#!/bin/bash 

while IFS= read -r -d '' file 
do 

    fileNew="${file%/*}"  # Everything before the last '\' 
    fileNew="${fileNew#*/}" # Everything after the last '\' 

    IFS="_" read _ _ folder <<<"$fileNew" 

    mv -v "$file" "/data/"$folder"/" 

done < <(find . -type f -name "result.dat" -print0) 
+0

感谢您的努力 –

相关问题