Bash脚本递归移动

问题描述 投票:0回答:1

我有这样的目录结构:

|--Photos  
   |--2014-01-15 #2  
      |--IMG_0045.JPG  
      |--IMG_0051.JPG  
   |--2014-06-19  
      |--IMG_0078.JPG  

请注意,一个文件夹的名称包含空格[2014-01-15#2]。我写了一个bash脚本,只使用这个来移动所有文件夹中的* .JPG文件:

#!/bin/bash
for i in $(ls); do  
    if [ -d $i ]; then
        cd $i
        mv *.JPG /opt/data/tmp/
        cd -
    fi
done  

据我所知,由于单词拆分,脚本没有进入名称包含空格的文件夹。

是否有一个bash脚本可以编写以便从所有文件夹中移动* .JPG文件?

bash shell
1个回答
1
投票

简单地说,mv */*.JPG /opt/data/tmp会按你的要求做。

您的脚本有两个常见的初学者错误。你需要put double quotes around all variables which contain file names,,你应该not be using ls to find files

就个人而言,我也建议不要在大多数脚本中使用cd

如果你需要在其他脚本中循环遍历目录,for i in ./*/; do就是这样做的。

如果你需要递归任意深度嵌套的目录,find会这样做。使用GNU find和GNU mvfind dir -type f -name '*.JPG' -exec mv -t /opt/data/tmp {} +

© www.soinside.com 2019 - 2024. All rights reserved.