【问题标题】:moving files to different directories将文件移动到不同的目录
【发布时间】:2011-12-11 06:55:57
【问题描述】:

我正在尝试将指定目录中的媒体和其他文件移动到另一个目录,如果它不退出(文件所在的位置),则创建另一个目录,并创建一个目录,其余具有不同扩展名的文件将去。我的第一个问题是我的脚本没有创建新目录,也没有将文件移动到其他目录,我可以使用什么代码将具有不同扩展名的文件移动到一个目录?

这是我到目前为止所拥有的,请纠正我的错误并帮助修改我的脚本:

#!/bin/bash
From=/home/katy/doc
To=/home/katy/mo #directory where the media files will go
WA=/home/katy/do # directory where the other files will go
 if [ ! -d "$To" ]; then
   mkdir -p "$To"
 fi
cd $From
find path -type f -name"*.mp4" -exec mv {} $To \;

【问题讨论】:

    标签: linux bash unix ubuntu


    【解决方案1】:

    我会这样解决它:

    #!/bin/bash
    From=/home/katy/doc
    To=/home/katy/mo # directory where the media files will go
    WA=/home/katy/do # directory where the other files will go
    
    cd "$From"
    find . -type f \
    | while read file; do
        dir="$(dirname "$file")"
        base="$(basename "$file")"
        if [[ "$file" =~ \.mp4$ ]]; then
          target="$To"
        else
          target="$WA"
        fi
        mkdir -p "$target/$dir"
        mv -i "$file" "$target/$dir/$base"
      done
    

    注意事项:

    • 如果目录已经存在,mkdir -p 不会抱怨,因此无需检查。
    • 在所有文件名两边加上双引号,以防它们包含空格。
    • 通过将find 的输出传送到while 循环中,您还可以避免被空格所困扰,因为read 会一直读取到换行符。
    • 您可以根据口味修改正则表达式,例如\.(mp3|mp4|wma|ogg)$
    • 如果您不知道,$(...) 将运行给定命令并将其输出粘贴回 $(...) 的位置(称为命令替换)。它与`...` 几乎相同,但略胜一筹(details)。
    • 为了测试它,把echo放在mv前面。 (请注意,引号将在输出中消失。)

    【讨论】:

      【解决方案2】:
      cd $From
      find . -type f -name "*.mp4" -exec mv {} $To \;
          ^^^
      

      find $From -type f -name "*.mp4" -exec mv {} $To \;
           ^^^^^
      

      【讨论】:

      • 我正在尝试但它不工作一个错误显示 can not mv:no such file or directory
      【解决方案3】:
      cd $From  
      mv *.mp4 $To;  
      mv * $WA;
      

      【讨论】:

      • 它告诉我目标不是目录
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 2013-04-14
      • 2013-06-10
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多