2016-11-25 59 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

感謝您的努力 –

相關問題