2016-11-07 127 views
0

我有一個像這樣的文件夾結構: 一個名爲Photos的大型父文件夾。該文件夾包含900多個子文件夾,分別命名爲a_000,a_001,a_002等。如何將文件從子文件夾移動到其父目錄(unix,終端)

每個子文件夾都包含更多的子文件夾,名爲dir_001,dir_002等。每個子文件夾都包含大量圖片(具有唯一名稱)。

我想將包含在a_xxx的子目錄中的所有這些圖片移動到a_xxx中。 (其中xxx可以是001,002等)

四處尋找類似的問題後,這是我想出了最接近的解決方案:

for file in *; do 
    if [ -d $file ]; then 
    cd $file; mv * ./; cd ..; 
    fi 
done 

另一種解決方案我正在做一個bash腳本:

#!/bin/bash 
dir1="/path/to/photos/" 
subs= `ls $dir1` 

for i in $subs; do 
    mv $dir1/$i/*/* $dir1/$i/ 
done 

不過,我錯過了一些東西,你能幫忙嗎?

(然後,它會很高興地丟棄空dir_yyy,但此刻沒有太大的問題)

+0

或許你也應該問這在Unix LINIX SE,因爲它是不是一個真正的編程問題,執行它。但作爲一個提示,在每個a_xxx目錄內部做一些事情,比如find。 -type f -exec mv \ {\}。 \;'可能是你在找什麼 – infixed

+0

嗨。我有900多個文件夾,但我不會爲每個文件夾都做這件事。如果SO不是發佈的地方,我很抱歉。就是在這裏我找到了更相關的例子:[link1](http://stackoverflow.com/questions/23546294/copy-files-from-subfolders-to-the-nearest-parent-directory-in-unix)和[ link2](http://stackoverflow.com/questions/22228718/using-for-loop-to-move-files-from-subdirectories-to-parent-directories) – Mpampirina

+0

確定關於'mv * ./;'部分?因爲在我看來,需要兩個點(用於父目錄),比如'mv * ../;'也許 – arhak

回答

2

你可以嘗試以下bash腳本:

#!/bin/bash 

#needed in case we have empty folders 
shopt -s nullglob 

#we must write the full path here (no ~ character) 
target="/path/to/photos" 

#we use a glob to list the folders. parsing the output of ls is baaaaaaaddd !!!! 
#for every folder in our photo folder ... 
for dir in "$target"/*/ 
do 
    #we list the subdirectories ... 
    for sub in "$dir"/*/ 
    do 
     #and we move the content of the subdirectories to the parent 
     mv "$sub"/* "$dir" 
     #if you want to remove subdirectories once the copy is done, uncoment the next line 
     #rm -r "$sub" 
    done 
done 

Here is why you don't parse ls in bash

1

確保在文件所在的目錄是正確的(和完整)在下面的腳本,並嘗試它:

#!/bin/bash 
BigParentDir=Photos 

for subdir in "$BigParentDir"/*/; do # Select the a_001, a_002 subdirs 
    for ssdir in "$subdir"/*/; do   # Select dir_001, … sub-subdirs 
    for f in "$ssdir"/*; do    # Select the files to move 
     if [[ -f $f ]]; do    # if indeed are files 
     echo \ 
     mv "$ssdir"/* "$subdir"/  # Move the files. 
     fi 
    done 
    done  
done 

沒有文件將被移動,只是打印。如果您確定該腳本能夠滿足您的要求,請評論回聲線並將其「真實」運行。

1

你可以試試這個

#!/bin/bash 
dir1="/path/to/photos/" 
subs= `ls $dir1` 

cp /dev/null /tmp/newscript.sh 

for i in $subs; do 
    find $dir1/$i -type f -exec echo mv \'\{\}\' $dir1/$i \; >> /tmp/newscript.sh 
done 

然後打開/tmp/newscript.sh使用編輯器或less,看模樣你正在努力去做。

,如果它再與sh -x /tmp/newscript.sh

相關問題