2016-11-07 213 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

相关问题